HTTP 方法
兩種最常見的 HTTP 方法是 GET 和 POST 。Flask 可以根據所使用的 HTTP 方法從相同的 URL 執行不同的程式碼。例如,在具有帳戶的 Web 服務中,最方便的是通過相同的 URL 路由登入頁面和登入過程。GET 請求(與你在瀏覽器中開啟 URL 時相同)應顯示登入表單,而 POST 請求(攜帶登入資料)應單獨處理。還建立了一個路由來處理 DELETE 和 PUT HTTP 方法。
@app.route("/login", methods=["GET"])
def login_form():
return "This is the login form"
@app.route("/login", methods=["POST"])
def login_auth():
return "Processing your data"
@app.route("/login", methods=["DELETE", "PUT"])
def deny():
return "This method is not allowed"
為了簡化程式碼,我們可以從 flask 匯入 request
包。
from flask import request
@app.route("/login", methods=["GET", "POST", "DELETE", "PUT"])
def login():
if request.method == "DELETE" or request.method == "PUT":
return "This method is not allowed"
elif request.method == "GET":
return "This is the login forum"
elif request.method == "POST":
return "Processing your data"
要從 POST 請求中檢索資料,我們必須使用 request
包:
from flask import request
@app.route("/login", methods=["GET", "POST", "DELETE", "PUT"])
def login():
if request.method == "DELETE" or request.method == "PUT":
return "This method is not allowed"
elif request.method == "GET":
return "This is the login forum"
elif request.method == "POST":
return "Username was " + request.form["username"] + " and password was " + request.form["password"]