HTTP 方法

两种最常见的 HTTP 方法是 GETPOST 。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"]