The Request Object
The Request
object encapsulates the incoming HTTP request. An instance of this class is automatically created by the framework and passed as the first argument (conventionally named req
) to your view functions.
It provides a clean, object-oriented interface to access all the details of the request, from the path and method to headers, cookies, and the request body.
Attributes
Here are the primary attributes you will use:
method
: The HTTP method of the request (e.g.,'GET'
,'POST'
).path
: The path component of the URL (e.g.,'/users/123'
).query
: A dictionary containing the parsed query string parameters. For a URL like/search?q=jsweb&page=2
,req.query
would be{'q': 'jsweb', 'page': '2'}
.headers
: A dictionary of incoming request headers. Header names are normalized to title case (e.g.,'User-Agent'
,'Content-Type'
).cookies
: A dictionary of cookies sent by the client.user
: The authenticated user object if the user is logged in, otherwiseNone
. This is populated by the authentication middleware.
Lazy-Loaded Attributes
To improve efficiency, the request body and form data are "lazy-loaded," meaning they are only read and parsed the first time you access them.
body
: The raw request body, decoded as a UTF-8 string. Accessing this for the first time reads the input stream from the WSGI server.form
: A dictionary containing data from a submitted form (withContent-Type: application/x-www-form-urlencoded
). Accessing this attribute will read and parse the request body.
Example Usage in a View
@app.route('/search', methods=['GET', 'POST'])
def search_view(req, res):
# Get the search term from the query string (for GET) or form (for POST)
search_term = ""
if req.method == 'POST':
search_term = req.form.get('q', '')
elif req.method == 'GET':
search_term = req.query.get('q', '')
# Get a header
user_agent = req.headers.get('User-Agent', 'Unknown')
# Get a cookie
session_id = req.cookies.get('session_id')
# Check for authenticated user
if req.user:
greeting = f"Hello, {req.user.username}!"
else:
greeting = "Hello, guest!"
return f"""
<h1>{greeting}</h1>
<p>You are searching for: {search_term}</p>
<p>Your User-Agent is: {user_agent}</p>
"""