Skip to content
Myr

reqcontext.rst

This file

Path

docs/reqcontext.rst

243 lines · 9.1 KiB

Last changed by

Merge pull request #5058 from pallets/require-blinkerDavid Lordbefore adoptiona05c0c6

History of this file

Take it

The walk stopped after 200 commits: lines older than 41aaaf7 point at it.

clean up unused function from prefixed_env prDavid Lordbefore adoption41aaaf7

lines 1–39why, 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.1011This is similar to :doc:`/appcontext`, which keeps track of the12application-level data independent of a request. A corresponding13application 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 request36context, which also pushes an :doc:`app context </appcontext>`. When the37request ends it pops the request context then the application context.3839The 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.

clean up unused function from prefixed_env prDavid Lordbefore adoption41aaaf7

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.

clean up unused function from prefixed_env prDavid Lordbefore adoption41aaaf7

lines 48–71why, 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):

Merge branch '2.2.x'David Lordbefore adoptiona18ae3d

line 72why, one step back
72 format = request.args.get("format")

clean up unused function from prefixed_env prDavid Lordbefore adoption41aaaf7

lines 73–75why, one step back
73 ...
7475 with app.test_request_context(

Merge branch '2.2.x'David Lordbefore adoptiona18ae3d

lines 76–77why, one step back
76 "/make_report/2017", query_string={"format": "short"}
77 ):

clean up unused function from prefixed_env prDavid Lordbefore adoption41aaaf7

lines 78–92why, one step back
78 generate_report()
7980If you see that error somewhere else in your code not related to81testing, it most likely indicates that you should move that code into a82view function.8384For information on how to use the request context from the interactive85Python shell, see :doc:`/shell`.868788How the Context Works89---------------------9091The :meth:`Flask.wsgi_app` method is called to handle each request. It92manages the contexts during the request. Internally, the request and

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

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

clean up unused function from prefixed_env prDavid Lordbefore adoption41aaaf7

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

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

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

clean up unused function from prefixed_env prDavid Lordbefore adoption41aaaf7

lines 96–103why, one step back
96
97When the request starts, a :class:`~ctx.RequestContext` is created and98pushed, which creates and pushes an :class:`~ctx.AppContext` first if99a context for that application is not already the top context. While100these contexts are pushed, the :data:`current_app`, :data:`g`,101:data:`request`, and :data:`session` proxies are available to the102original thread handling the request.103

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

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

clean up unused function from prefixed_env prDavid Lordbefore adoption41aaaf7

lines 108–206why, one step back
108
109After the request is dispatched and a response is generated and sent,110the request context is popped, which then pops the application context.111Immediately before they are popped, the :meth:`~Flask.teardown_request`112and :meth:`~Flask.teardown_appcontext` functions are executed. These113execute even if an unhandled exception occurred during dispatch.114115116.. _callbacks-and-errors:117118Callbacks and Errors119--------------------120121Flask dispatches a request in multiple stages which can affect the122request, response, and how errors are handled. The contexts are active123during all of these stages.124125A :class:`Blueprint` can add handlers for these events that are specific126to the blueprint. The handlers for a blueprint will run if the blueprint127owns the route that matches the request.128129#. Before each request, :meth:`~Flask.before_request` functions are130 called. If one of these functions return a value, the other131 functions are skipped. The return value is treated as the response132 and the view function is not called.133134#. If the :meth:`~Flask.before_request` functions did not return a135 response, the view function for the matched route is called and136 returns a response.137138#. The return value of the view is converted into an actual response139 object and passed to the :meth:`~Flask.after_request`140 functions. Each function returns a modified or new response object.141142#. After the response is returned, the contexts are popped, which calls143 the :meth:`~Flask.teardown_request` and144 :meth:`~Flask.teardown_appcontext` functions. These functions are145 called even if an unhandled exception was raised at any point above.146147If an exception is raised before the teardown functions, Flask tries to148match it with an :meth:`~Flask.errorhandler` function to handle the149exception and return a response. If no error handler is found, or the150handler itself raises an exception, Flask returns a generic151``500 Internal Server Error`` response. The teardown functions are still152called, and are passed the exception object.153154If debug mode is enabled, unhandled exceptions are not converted to a155``500`` response and instead are propagated to the WSGI server. This156allows the development server to present the interactive debugger with157the traceback.158159160Teardown Callbacks161~~~~~~~~~~~~~~~~~~162163The teardown callbacks are independent of the request dispatch, and are164instead called by the contexts when they are popped. The functions are165called even if there is an unhandled exception during dispatch, and for166manually pushed contexts. This means there is no guarantee that any167other parts of the request dispatch have run first. Be sure to write168these functions in a way that does not depend on other callbacks and169will not fail.170171During testing, it can be useful to defer popping the contexts after the172request ends, so that their data can be accessed in the test function.173Use the :meth:`~Flask.test_client` as a ``with`` block to preserve the174contexts until the ``with`` block exits.175176.. code-block:: python177178 from flask import Flask, request179180 app = Flask(__name__)181182 @app.route('/')183 def hello():184 print('during view')185 return 'Hello, World!'186187 @app.teardown_request188 def show_teardown(exception):189 print('after with block')190191 with app.test_request_context():192 print('during with block')193194 # teardown functions are called after the context with block exits195196 with app.test_client() as client:197 client.get('/')198 # the contexts are not popped even though the request ended199 print(request.path)200201 # the contexts are popped and teardown functions are called after202 # the client with block exits203204Signals205~~~~~~~206

Merge pull request #5058 from pallets/require-blinkerDavid Lordbefore adoptiona05c0c6

line 207why, one step back
207The following signals are sent:

clean up unused function from prefixed_env prDavid Lordbefore adoption41aaaf7

line 208why, one step back
208

Merge pull request #5058 from pallets/require-blinkerDavid Lordbefore adoptiona05c0c6

lines 209–216why, one step back
209#. :data:`request_started` is sent before the :meth:`~Flask.before_request` functions
210 are called.211#. :data:`request_finished` is sent after the :meth:`~Flask.after_request` functions212 are called.213#. :data:`got_request_exception` is sent when an exception begins to be handled, but214 before an :meth:`~Flask.errorhandler` is looked up or called.215#. :data:`request_tearing_down` is sent after the :meth:`~Flask.teardown_request`216 functions are called.

clean up unused function from prefixed_env prDavid Lordbefore adoption41aaaf7

lines 217–243why, one step back
217
218219.. _notes-on-proxies:220221Notes On Proxies222----------------223224Some of the objects provided by Flask are proxies to other objects. The225proxies are accessed in the same way for each worker thread, but226point to the unique object bound to each worker behind the scenes as227described on this page.228229Most of the time you don't have to care about that, but there are some230exceptions where it is good to know that this object is actually a proxy:231232- The proxy objects cannot fake their type as the actual object types.233 If you want to perform instance checks, you have to do that on the234 object being proxied.235- The reference to the proxied object is needed in some situations,236 such as sending :doc:`signals` or passing data to a background237 thread.238239If you need to access the underlying object that is proxied, use the240:meth:`~werkzeug.local.LocalProxy._get_current_object` method::241242 app = current_app._get_current_object()243 my_signal.send(app)