Skip to content
Myr

reqcontext.rst

This file

Path

docs/reqcontext.rst

247 lines · 9.2 KiB

Last changed by

Merge pull request #4682 from pallets/refactor-context-stackDavid Lordbefore adoptioncbebdae

History of this file

Take it

The walk stopped after 200 commits: lines older than 50eb6e5 point at it.

Merge pull request #3856 from pallets/dependabot/pip/pre-commit-2.9.3dependabot-preview[bot]before adoption50eb6e5

lines 1–10why, one step back
1.. currentmodule:: flask
23The Request Context4===================56The request context keeps track of the request-level data during a7request. Rather than passing the request object to each function that8runs during a request, the :data:`request` and :data:`session` proxies9are accessed instead.10

Merge branch '2.0.x'David Lordbefore adoption5684f48

line 11why, one step back
11This is similar to :doc:`/appcontext`, which keeps track of the

Merge pull request #3856 from pallets/dependabot/pip/pre-commit-2.9.3dependabot-preview[bot]before adoption50eb6e5

lines 12–35why, one step back
12application-level data independent of a request. A corresponding
13application context is pushed when a request context is pushed.141516Purpose of the Context17----------------------1819When the :class:`Flask` application handles a request, it creates a20:class:`Request` object based on the environment it received from the21WSGI server. Because a *worker* (thread, process, or coroutine depending22on the server) handles only one request at a time, the request data can23be considered global to that worker during that request. Flask uses the24term *context local* for this.2526Flask automatically *pushes* a request context when handling a request.27View functions, error handlers, and other functions that run during a28request will have access to the :data:`request` proxy, which points to29the request object for the current request.303132Lifetime of the Context33-----------------------3435When a Flask application begins handling a request, it pushes a request

Merge branch '2.0.x'David Lordbefore adoption5684f48

lines 36–37why, one step back
36context, which also pushes an :doc:`app context </appcontext>`. When the
37request ends it pops the request context then the application context.

Merge pull request #3856 from pallets/dependabot/pip/pre-commit-2.9.3dependabot-preview[bot]before adoption50eb6e5

lines 38–39why, one step back
38
39The context is unique to each thread (or other worker type).

Merge pull request #4682 from pallets/refactor-context-stackDavid Lordbefore adoptioncbebdae

lines 40–42why, one step back
40:data:`request` cannot be passed to another thread, the other thread has
41a different context space and will not know about the request the parent42thread was pointing to.

Merge pull request #3856 from pallets/dependabot/pip/pre-commit-2.9.3dependabot-preview[bot]before adoption50eb6e5

line 43why, one step back
43

Merge pull request #4682 from pallets/refactor-context-stackDavid Lordbefore adoptioncbebdae

lines 44–47why, one step back
44Context locals are implemented using Python's :mod:`contextvars` and
45Werkzeug's :class:`~werkzeug.local.LocalProxy`. Python manages the46lifetime of context vars automatically, and local proxy wraps that47low-level interface to make the data easier to work with.

Merge pull request #3856 from pallets/dependabot/pip/pre-commit-2.9.3dependabot-preview[bot]before adoption50eb6e5

lines 48–91why, one step back
48
4950Manually Push a Context51-----------------------5253If you try to access :data:`request`, or anything that uses it, outside54a request context, you'll get this error message:5556.. code-block:: pytb5758 RuntimeError: Working outside of request context.5960 This typically means that you attempted to use functionality that61 needed an active HTTP request. Consult the documentation on testing62 for information about how to avoid this problem.6364This should typically only happen when testing code that expects an65active request. One option is to use the66:meth:`test client <Flask.test_client>` to simulate a full request. Or67you can use :meth:`~Flask.test_request_context` in a ``with`` block, and68everything that runs in the block will have access to :data:`request`,69populated with your test data. ::7071 def generate_report(year):72 format = request.args.get('format')73 ...7475 with app.test_request_context(76 '/make_report/2017', data={'format': 'short'}):77 generate_report()7879If you see that error somewhere else in your code not related to80testing, it most likely indicates that you should move that code into a81view function.8283For information on how to use the request context from the interactive84Python shell, see :doc:`/shell`.858687How the Context Works88---------------------8990The :meth:`Flask.wsgi_app` method is called to handle each request. It91manages the contexts during the request. Internally, the request and

Merge pull request #4682 from pallets/refactor-context-stackDavid Lordbefore adoptioncbebdae

line 92why, one step back
92application contexts work like stacks. When contexts are pushed, the

Merge pull request #3856 from pallets/dependabot/pip/pre-commit-2.9.3dependabot-preview[bot]before adoption50eb6e5

line 93why, one step back
93proxies that depend on them are available and point at information from

Merge pull request #4682 from pallets/refactor-context-stackDavid Lordbefore adoptioncbebdae

line 94why, one step back
94the top item.

Merge pull request #3856 from pallets/dependabot/pip/pre-commit-2.9.3dependabot-preview[bot]before adoption50eb6e5

lines 95–102why, one step back
95
96When the request starts, a :class:`~ctx.RequestContext` is created and97pushed, which creates and pushes an :class:`~ctx.AppContext` first if98a context for that application is not already the top context. While99these contexts are pushed, the :data:`current_app`, :data:`g`,100:data:`request`, and :data:`session` proxies are available to the101original thread handling the request.102

Merge pull request #4682 from pallets/refactor-context-stackDavid Lordbefore adoptioncbebdae

lines 103–106why, one step back
103Other contexts may be pushed to change the proxies during a request.
104While this is not a common pattern, it can be used in advanced105applications to, for example, do internal redirects or chain different106applications together.

Merge pull request #3856 from pallets/dependabot/pip/pre-commit-2.9.3dependabot-preview[bot]before adoption50eb6e5

lines 107–247why, one step back
107
108After the request is dispatched and a response is generated and sent,109the request context is popped, which then pops the application context.110Immediately before they are popped, the :meth:`~Flask.teardown_request`111and :meth:`~Flask.teardown_appcontext` functions are executed. These112execute even if an unhandled exception occurred during dispatch.113114115.. _callbacks-and-errors:116117Callbacks and Errors118--------------------119120Flask dispatches a request in multiple stages which can affect the121request, response, and how errors are handled. The contexts are active122during all of these stages.123124A :class:`Blueprint` can add handlers for these events that are specific125to the blueprint. The handlers for a blueprint will run if the blueprint126owns the route that matches the request.127128#. Before each request, :meth:`~Flask.before_request` functions are129 called. If one of these functions return a value, the other130 functions are skipped. The return value is treated as the response131 and the view function is not called.132133#. If the :meth:`~Flask.before_request` functions did not return a134 response, the view function for the matched route is called and135 returns a response.136137#. The return value of the view is converted into an actual response138 object and passed to the :meth:`~Flask.after_request`139 functions. Each function returns a modified or new response object.140141#. After the response is returned, the contexts are popped, which calls142 the :meth:`~Flask.teardown_request` and143 :meth:`~Flask.teardown_appcontext` functions. These functions are144 called even if an unhandled exception was raised at any point above.145146If an exception is raised before the teardown functions, Flask tries to147match it with an :meth:`~Flask.errorhandler` function to handle the148exception and return a response. If no error handler is found, or the149handler itself raises an exception, Flask returns a generic150``500 Internal Server Error`` response. The teardown functions are still151called, and are passed the exception object.152153If debug mode is enabled, unhandled exceptions are not converted to a154``500`` response and instead are propagated to the WSGI server. This155allows the development server to present the interactive debugger with156the traceback.157158159Teardown Callbacks160~~~~~~~~~~~~~~~~~~161162The teardown callbacks are independent of the request dispatch, and are163instead called by the contexts when they are popped. The functions are164called even if there is an unhandled exception during dispatch, and for165manually pushed contexts. This means there is no guarantee that any166other parts of the request dispatch have run first. Be sure to write167these functions in a way that does not depend on other callbacks and168will not fail.169170During testing, it can be useful to defer popping the contexts after the171request ends, so that their data can be accessed in the test function.172Use the :meth:`~Flask.test_client` as a ``with`` block to preserve the173contexts until the ``with`` block exits.174175.. code-block:: python176177 from flask import Flask, request178179 app = Flask(__name__)180181 @app.route('/')182 def hello():183 print('during view')184 return 'Hello, World!'185186 @app.teardown_request187 def show_teardown(exception):188 print('after with block')189190 with app.test_request_context():191 print('during with block')192193 # teardown functions are called after the context with block exits194195 with app.test_client() as client:196 client.get('/')197 # the contexts are not popped even though the request ended198 print(request.path)199200 # the contexts are popped and teardown functions are called after201 # the client with block exits202203Signals204~~~~~~~205206If :data:`~signals.signals_available` is true, the following signals are207sent:208209#. :data:`request_started` is sent before the210 :meth:`~Flask.before_request` functions are called.211212#. :data:`request_finished` is sent after the213 :meth:`~Flask.after_request` functions are called.214215#. :data:`got_request_exception` is sent when an exception begins to216 be handled, but before an :meth:`~Flask.errorhandler` is looked up or217 called.218219#. :data:`request_tearing_down` is sent after the220 :meth:`~Flask.teardown_request` functions are called.221222223.. _notes-on-proxies:224225Notes On Proxies226----------------227228Some of the objects provided by Flask are proxies to other objects. The229proxies are accessed in the same way for each worker thread, but230point to the unique object bound to each worker behind the scenes as231described on this page.232233Most of the time you don't have to care about that, but there are some234exceptions where it is good to know that this object is actually a proxy:235236- The proxy objects cannot fake their type as the actual object types.237 If you want to perform instance checks, you have to do that on the238 object being proxied.239- The reference to the proxied object is needed in some situations,240 such as sending :doc:`signals` or passing data to a background241 thread.242243If you need to access the underlying object that is proxied, use the244:meth:`~werkzeug.local.LocalProxy._get_current_object` method::245246 app = current_app._get_current_object()247 my_signal.send(app)