請求物件

request 物件提供有關對路由發出的請求的資訊。要使用此物件,必須從 Flask 模組匯入:

from flask import request

網址引數

在之前的示例中,使用了 request.methodrequest.form,但是我們也可以使用 request.args 屬性來檢索 URL 引數中的鍵/值的字典。

@app.route("/api/users/<username>")
def user_api(username):
    try:
        token = request.args.get("key")
        if key == "pA55w0Rd":
            if isUser(username): # The code of this method is irrelevant
                joined = joinDate(username) # The code of this method is irrelevant
                return "User " + username + " joined on " + joined
            else:
                return "User not found"
        else:
            return "Incorrect key"
    # If there is no key parameter
    except KeyError:
        return "No key provided"

要在此上下文中正確進行身份驗證,需要以下 URL(用任何使用者名稱替換使用者名稱:

www.example.com/api/users/guido-van-rossum?key=pa55w0Rd

檔案上傳

如果檔案上載是 POST 請求中提交的表單的一部分,則可以使用 request 物件處理檔案:

@app.route("/upload", methods=["POST"])
def upload_file():
    f = request.files["wordlist-upload"]
    f.save("/var/www/uploads/" + f.filename) # Store with the original filename

餅乾

該請求還可以包括類似於 URL 引數的字典中的 cookie。

@app.route("/home")
def home():
    try:
        username = request.cookies.get("username")
        return "Your stored username is " + username
    except KeyError:
        return "No username cookies was found")