Skip to content
Myr

reqcontext.rst

This file

Path

docs/reqcontext.rst

265 lines · 9.9 KiB

Last changed by

Merge pull request #4267 from sprutner/patch-1David Lordbefore adoptionf8c881b

History of this file

Take it

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

Merge pull request #3723 from greyli/fix-intersphinx-linkGrey Libefore adoptionfd0f89e

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 pull request #4267 from sprutner/patch-1David Lordbefore adoptionf8c881b

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

Merge pull request #3723 from greyli/fix-intersphinx-linkGrey Libefore adoptionfd0f89e

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 pull request #4267 from sprutner/patch-1David Lordbefore adoptionf8c881b

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 #3723 from greyli/fix-intersphinx-linkGrey Libefore adoptionfd0f89e

lines 38–265why, one step back
38
39The context is unique to each thread (or other worker type).40:data:`request` cannot be passed to another thread, the other thread41will have a different context stack and will not know about the request42the parent thread was pointing to.4344Context locals are implemented in Werkzeug. See :doc:`werkzeug:local`45for more information on how this works internally.464748Manually Push a Context49-----------------------5051If you try to access :data:`request`, or anything that uses it, outside52a request context, you'll get this error message:5354.. code-block:: pytb5556 RuntimeError: Working outside of request context.5758 This typically means that you attempted to use functionality that59 needed an active HTTP request. Consult the documentation on testing60 for information about how to avoid this problem.6162This should typically only happen when testing code that expects an63active request. One option is to use the64:meth:`test client <Flask.test_client>` to simulate a full request. Or65you can use :meth:`~Flask.test_request_context` in a ``with`` block, and66everything that runs in the block will have access to :data:`request`,67populated with your test data. ::6869 def generate_report(year):70 format = request.args.get('format')71 ...7273 with app.test_request_context(74 '/make_report/2017', data={'format': 'short'}):75 generate_report()7677If you see that error somewhere else in your code not related to78testing, it most likely indicates that you should move that code into a79view function.8081For information on how to use the request context from the interactive82Python shell, see :doc:`/shell`.838485How the Context Works86---------------------8788The :meth:`Flask.wsgi_app` method is called to handle each request. It89manages the contexts during the request. Internally, the request and90application contexts work as stacks, :data:`_request_ctx_stack` and91:data:`_app_ctx_stack`. When contexts are pushed onto the stack, the92proxies that depend on them are available and point at information from93the top context on the stack.9495When the request starts, a :class:`~ctx.RequestContext` is created and96pushed, which creates and pushes an :class:`~ctx.AppContext` first if97a context for that application is not already the top context. While98these contexts are pushed, the :data:`current_app`, :data:`g`,99:data:`request`, and :data:`session` proxies are available to the100original thread handling the request.101102Because the contexts are stacks, other contexts may be pushed to change103the proxies during a request. While this is not a common pattern, it104can be used in advanced applications to, for example, do internal105redirects or chain different applications together.106107After the request is dispatched and a response is generated and sent,108the request context is popped, which then pops the application context.109Immediately before they are popped, the :meth:`~Flask.teardown_request`110and :meth:`~Flask.teardown_appcontext` functions are executed. These111execute even if an unhandled exception occurred during dispatch.112113114.. _callbacks-and-errors:115116Callbacks and Errors117--------------------118119Flask dispatches a request in multiple stages which can affect the120request, response, and how errors are handled. The contexts are active121during all of these stages.122123A :class:`Blueprint` can add handlers for these events that are specific124to the blueprint. The handlers for a blueprint will run if the blueprint125owns the route that matches the request.126127#. Before each request, :meth:`~Flask.before_request` functions are128 called. If one of these functions return a value, the other129 functions are skipped. The return value is treated as the response130 and the view function is not called.131132#. If the :meth:`~Flask.before_request` functions did not return a133 response, the view function for the matched route is called and134 returns a response.135136#. The return value of the view is converted into an actual response137 object and passed to the :meth:`~Flask.after_request`138 functions. Each function returns a modified or new response object.139140#. After the response is returned, the contexts are popped, which calls141 the :meth:`~Flask.teardown_request` and142 :meth:`~Flask.teardown_appcontext` functions. These functions are143 called even if an unhandled exception was raised at any point above.144145If an exception is raised before the teardown functions, Flask tries to146match it with an :meth:`~Flask.errorhandler` function to handle the147exception and return a response. If no error handler is found, or the148handler itself raises an exception, Flask returns a generic149``500 Internal Server Error`` response. The teardown functions are still150called, and are passed the exception object.151152If debug mode is enabled, unhandled exceptions are not converted to a153``500`` response and instead are propagated to the WSGI server. This154allows the development server to present the interactive debugger with155the traceback.156157158Teardown Callbacks159~~~~~~~~~~~~~~~~~~160161The teardown callbacks are independent of the request dispatch, and are162instead called by the contexts when they are popped. The functions are163called even if there is an unhandled exception during dispatch, and for164manually pushed contexts. This means there is no guarantee that any165other parts of the request dispatch have run first. Be sure to write166these functions in a way that does not depend on other callbacks and167will not fail.168169During testing, it can be useful to defer popping the contexts after the170request ends, so that their data can be accessed in the test function.171Use the :meth:`~Flask.test_client` as a ``with`` block to preserve the172contexts until the ``with`` block exits.173174.. code-block:: python175176 from flask import Flask, request177178 app = Flask(__name__)179180 @app.route('/')181 def hello():182 print('during view')183 return 'Hello, World!'184185 @app.teardown_request186 def show_teardown(exception):187 print('after with block')188189 with app.test_request_context():190 print('during with block')191192 # teardown functions are called after the context with block exits193194 with app.test_client() as client:195 client.get('/')196 # the contexts are not popped even though the request ended197 print(request.path)198199 # the contexts are popped and teardown functions are called after200 # the client with block exits201202Signals203~~~~~~~204205If :data:`~signals.signals_available` is true, the following signals are206sent:207208#. :data:`request_started` is sent before the209 :meth:`~Flask.before_request` functions are called.210211#. :data:`request_finished` is sent after the212 :meth:`~Flask.after_request` functions are called.213214#. :data:`got_request_exception` is sent when an exception begins to215 be handled, but before an :meth:`~Flask.errorhandler` is looked up or216 called.217218#. :data:`request_tearing_down` is sent after the219 :meth:`~Flask.teardown_request` functions are called.220221222Context Preservation on Error223-----------------------------224225At the end of a request, the request context is popped and all data226associated with it is destroyed. If an error occurs during development,227it is useful to delay destroying the data for debugging purposes.228229When the development server is running in development mode (the230``FLASK_ENV`` environment variable is set to ``'development'``), the231error and data will be preserved and shown in the interactive debugger.232233This behavior can be controlled with the234:data:`PRESERVE_CONTEXT_ON_EXCEPTION` config. As described above, it235defaults to ``True`` in the development environment.236237Do not enable :data:`PRESERVE_CONTEXT_ON_EXCEPTION` in production, as it238will cause your application to leak memory on exceptions.239240241.. _notes-on-proxies:242243Notes On Proxies244----------------245246Some of the objects provided by Flask are proxies to other objects. The247proxies are accessed in the same way for each worker thread, but248point to the unique object bound to each worker behind the scenes as249described on this page.250251Most of the time you don't have to care about that, but there are some252exceptions where it is good to know that this object is actually a proxy:253254- The proxy objects cannot fake their type as the actual object types.255 If you want to perform instance checks, you have to do that on the256 object being proxied.257- The reference to the proxied object is needed in some situations,258 such as sending :doc:`signals` or passing data to a background259 thread.260261If you need to access the underlying object that is proxied, use the262:meth:`~werkzeug.local.LocalProxy._get_current_object` method::263264 app = current_app._get_current_object()265 my_signal.send(app)