The Request Object
suggest changeThe request object provides information on the request that was made to the route. To utilize this object, it must be imported from the flask module:
from flask import request
URL Parameters
In previous examples request.method and request.form were used, however we can also use the request.args property to retrieve a dictionary of the keys/values in the URL parameters.
@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"
To correctly authenticate in this context, the following URL would be needed (replacing the username with any username):
www.example.com/api/users/guido-van-rossum?key=pa55w0Rd
The comparison uses key, which was never assigned (token holds the query value), so this raises NameError. request.args.get returns None when key is absent and does not raise KeyError. The URL uses pa55w0Rd, which does not match pA55w0Rd.
File Uploads
If a file upload was part of the submitted form in a POST request, the files can be handled using the request object:
@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
f.filename is joined onto the directory as given, so a name containing a path can escape /var/www/uploads/. The view also returns nothing.
Cookies
The request may also include cookies in a dictionary similar to the URL parameters.
@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")
The return line has an extra ), so this block is a syntax error. request.cookies.get returns None instead of raising KeyError, and "..." + None then raises TypeError. The message also says "cookies was".