Request Context (Flask)

The request context in Flask holds data tied to a single incoming request and powers the request and session proxies. Flask pushes it automatically while handling each request and pops it when the response is sent.

Flask

Where the application context answers 'which app', the request context answers 'which request', making request and session refer to the data of the call currently being handled. This is what lets concurrent requests use the same global names without interfering.

Pushing a request context also pushes an application context if one is not already active, so request work always has access to current_app and g too. You rarely push it yourself except in tests, where app.test_request_context() lets you exercise code that reads request data.

Trying to access request outside a request (e.g. in a background thread spawned from a view) raises 'Working outside of request context', signaling you need to capture the data you need before leaving the request.

Syntax

with app.test_request_context("/?q=hi"):
    request.args.get("q")

Examples

Python

from flask import request

with app.test_request_context("/search?q=flask"):
    print(request.args.get("q"))

Output:

flask

Learn it in a lesson

See also

Back to the Dictionary