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:

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.

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>
    """