一、Flask概述
1、什么是Web Framework?
Web Application Framework(web應用程序框架)或簡單的Web Framework(web框架)表示一個庫和模塊的集合,使web應用程序開發人員能夠編寫應用程序,而不必擔心協議,線程管理等極地細節。
2、WSGI
Web Server Gateway Interface(web服務器網關接口,WSGI),已被用作python web應用程序開發的標准,WSGI是Web服務器和Web應用程序之間通用接口的規范。
3、什么是Flask?
Flask是一個用python編寫的Web應用程序框架,其基於Werkzeug WSGI工具包和Jinja2模版引擎。
4、Werkzeug
它是一個WSGI工具包,它實現了請求,響應對象和實用函數。這使得能夠在其上構建web框架。Flask框架是Werkzeug作為其基礎之一。
5、Jinja2
Jinja2是Python的一個流行的模板引擎。Web模板系統將模板與特定數據源組合以呈現動態網頁。
Flask通常被稱為微服務,它目的在保持應用程序的核心簡單且可擴展。
二、Flask HTTP方法
HTTP協議是萬維網中數據通信的基礎,在該協議中定義了從指定URL檢索數據的不同方法。
序號 | 方法和描述 |
GET | 以未加密的形式將數據發送給服務器 |
HEAD | 和GET方法相同,但沒有響應體 |
POST | 用於將HTML表單數據發送到服務器,POST方法接收到數據不由服務器緩存 |
PUT | 用上傳到內容替換目標資源的所有當前表示 |
DELETE | 刪除有URL給出的目標資源的所有當前表示 |
三、Flask Request對象
來自客戶端網頁的數據作為全局請求對象發送到服務器,為了處理請求數據,應該從Flask模塊導入。
Request對象的重要屬性如下所列:
- Form - 它是一個字典對象,包含了表單參數及其鍵值對
- args - 解析查詢字符串的內容,它是問號(?)之后的URL的一部分
- Cookies - 保存Cookie名稱和值的字典對象
- files - 與上傳文件有關的數據
- method - 當前請求方法
四、Flask將表單數據發送到模板
當前,可以在URL規則中指定http方法,觸發函數接收到Form數據可以從字典對象的形式收集它,並將其轉發到模板以在相應的網頁上呈現它。
案列:
准備一個提交表單
app.py
from flask import Flask,render_template, request import os """ Flask類的一個對象是我們web服務器網關接口(WSGI) Flask構造函數使用當前模塊(__name__)的名稱作為參數 """ # 獲取 template和static的路徑 template_folder = os.getcwd() + '/apps/templates' static_folder = os.getcwd() + '/apps/static' app = Flask(__name__,template_folder=template_folder, static_folder=static_folder) @app.route('/') def student():
"""提交表單""" return render_template('student.html') @app.route('/result',methods = ['POST', 'GET']) def result(): if request.method == 'POST': result = request.form return render_template("result.html", result = result) if __name__ == '__main__': app.run(debug=True)
student.html
<form action="http://localhost:5000/result" method="POST"> <p>Name <input type = "text" name = "Name" /></p> <p>Physics <input type = "text" name = "Physics" /></p> <p>Chemistry <input type = "text" name = "chemistry" /></p> <p>Maths <input type ="text" name = "Mathematics" /></p> <p><input type = "submit" value = "submit" /></p> </form>
result.htm
<!doctype html> <table border = 1> {% for key, value in result.items() %} <tr> <th> {{ key }} </th> <td> {{ value }}</td> </tr> {% endfor %} </table>
五、Flask Cookie
Cookie以文本文件的形式存儲在客戶端的計算機上。其目的是記住和追蹤與客戶使用相關的數據,以獲得更好的訪問者體驗和網站統計信息。Request對象包含cookie的屬性,它是所有cookie變量及其對應值的字典對象,客戶端已傳輸。除此之外,cokkie還存儲其網站的到期時間、路徑和域名。
在Flask中,對cookie的處理步驟為:
1、設置cookie
設置cookie,默認有效期是臨時cookie,瀏覽器關閉就失效;
可以通過max_age設置有效期,單位是秒
resp = make_response("success"). #設置響應體 resp.set_cookie("w3chool", "w3chool", max_age=3600)
2、獲取cookie
獲取cookie,通過request.cookies的方式,返回的是一個詞典,可以獲取字典里的相應的值。
cookie_1 = request.cookies.get("w3school")
3、刪除cookie
這里的刪除只是讓cookie過期,並不是直接刪除cookie。刪除cookie,通過delete_cookie()的方式,里面有cookie的名字。
resp = make_response("del success") # 設置響應體 resp.delete_cookie("w3cshool")
簡單實例;
from flask import Flask, make_response, request apps = Flask(__name__) @apps.route("/set_cookies") def set_cookie(): resp = make_response("suceess") resp.set_cookie("w3cshool", "w3cshool", max_age=3600) return resp @apps.route('/get_cookies') def get_cookie(): cookie_1 = request.cookies.get("w3cshool") return cookie_1 @apps.route('/delete_cookies') def delete_cookie(): resp = make_response("del success") resp.delete_cookie("w3cshool") return resp if __name__ == "__main__": apps.run(debug=True)
六、Flask 會話
與cookie不同,Session(會話)數據存儲在服務器上,會話是客戶端登錄到服務器並注銷服務器的時間間隔。需要在該會話中保存到數據會存儲在服務器上的臨時目錄中。為每個客戶端會話分配會話ID,會話數據存儲在cookie的頂部,服務器以加密方式對其進行簽名,對於此加密,Flask應用程序需要一個定義的SECRET_KEY。
session對象也是一個字典對象,包含會話變量和關聯值的鍵值對。
from flask import Flask, session, redirect, url_for, escape, request apps = Flask(__name__) apps.secret_key = "fkdjsafjdkfdlkjfadskjfadskljdsfklj" @apps.route('/') def index(): if 'username' in session: username = session['username'] return '登錄用戶名是:' + username + '<br>' + \ "<b><a href = '/logout'>點擊這里注銷</a></b>" return "您暫未登錄, <br><a href = '/login'></b>" + \ "點擊這里登錄</b></a>" @apps.route('/login', methods = ['GET', 'POST']) def login(): if request.method == 'POST': session['username'] = request.form['username'] return redirect(url_for('index')) return ''' <form action = "" method = "post"> <p><input type="text" name="username"/></p> <p><input type="submit" value ="登錄"/></p> </form> ''' @apps.route('/logout') def logout(): # remove the username form the session if it is there session.pop('username', None) return redirect(url_for('index')) if __name__ == '__main__': apps.run(debug=True)
七、Flask重定向和錯誤
Flask類有一個redirect()函數,調用時,它返回一個響應對象,並將用戶重定向到具有指定狀態代碼到另一個目標位置。
redirect()函數的原型如下:
Flask.redirect(location, statuscode, response)
- location 參數是應該重定向響應的URL
- statuscode 發送到瀏覽器標頭,默認是302
- response 用於實例化響應
八、Flask消息閃現
Flask提供了一個非常簡單的方法來使用閃現系統向用戶反饋信息。閃現系統使得在一個請求結束的時候記錄一個信息,然后當且在下一個請求中訪問這個數據,強調flask閃現是基於flask內置的session的,利用瀏覽器的session緩存閃現消息,所以必須設置secret_key。
在Flask web應用應用程序中生成這樣的信息很容易。Flask框架的閃現系統可以在一個視圖中創建消息,並在名為next的視圖函數中呈現它。Flask模塊包含flash()方法,它將消息傳遞給下一個請求,該請求通常是一個模板。
flash(message, category)
- message 要閃現的實際消息
- category 是可選的,它可以是'error','info' 或 'warning'
為了從會話中刪除消息,模板調用get_flashed_messages()
get_flashed_messages(with_categories, category_filter)
兩個參數都是可選的,如果接收到的消息具有類別,則第一個參數是元組,第二個參數僅用於顯示特定消息
{% with messages = get_flashed_messages() %}
{% if messages %}
{% for message in messages %}
{{ message }}
{% endfor %}
{% endif %}
{% endwith %}
例:
在'/' URL 顯示登錄頁面的鏈接,沒有消息閃現,該鏈接會將用戶引導到'/login' URL,該 URL 顯示登錄表單。提交時,login() 視圖函數驗證用戶名和密碼,並相應閃現 'success' 消息或創建 'error' 變量。
from flask import Flask,request,flash,redirect,url_for,render_template import os template_folder = os.getcwd() + '/apps/templates' static_folder = os.getcwd() + '/apps/static' apps = Flask(__name__,template_folder=template_folder, static_folder=static_folder) apps.secret_key = "fkdjsafjdkfdlkjfadskjfadskljdsfklj" @apps.route('/') def index(): return render_template('index.html') @apps.route('/login', methods = ['GET', 'POST']) def login(): error = None if request.method == 'POST': if request.form['username'] != 'admin' or request.form['password'] != 'admin': error = 'Invalid username or password. Please try again!' else: flash("You were successfully logged in") return redirect(url_for('index')) return render_template('login.html', error = error) if __name__ == "__main__": apps.run(debug=True)
login.html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Login</title> </head> <body> <form method = "post" action = "http://localhost:5000/login"> <table> <tr> <td>Username</td> <td><input type = 'username' name = 'username'></td> </tr> <tr> <td>Password</td> <td><input type = 'password' name = 'password'></td> </tr> <tr> <td><input type = "submit" value = "Submit"></td> </tr> </table> </form> {% if error %} <p><strong>Error</strong>: {{ error }}</p> {% endif %} </body> </html>
Index.html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Index</title> </head> <body> {% with messages = get_flashed_messages() %} {% if messages %} {% for message in messages %} <p>{{ message }}</p> {% endfor %} {% endif %} {% endwith %} <h3>Welcome!</h3> <a href = "{{ url_for('login') }}">login</a> </body> </html>