请求对象
request
对象提供有关对路由发出的请求的信息。要使用此对象,必须从 Flask 模块导入:
from flask import request
网址参数
在之前的示例中,使用了 request.method
和 request.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")