Skip to content
Myr

reqcontext.rst

This file

Path

docs/reqcontext.rst

266 lines · 9.9 KiB

Last changed by

doc reqcontext fix teardown example (#2892)Alexis Benoistbefore adoptionb9b88b0

History of this file

Take it

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

Merge pull request #2685 from davidism/app-context-docsDavid Lordbefore adoption16d83d6

lines 1–2why, one step back
1.. currentmodule:: flask
2

Merge remote-tracking branch 'upstream/0.12-maintenance'Adrian Moennichbefore adoptioneb1c2fa

lines 3–7why, one step back
3.. _request-context:
45The Request Context6===================7

Merge pull request #2685 from davidism/app-context-docsDavid Lordbefore adoption16d83d6

lines 8–11why, one step back
8The request context keeps track of the request-level data during a
9request. Rather than passing the request object to each function that10runs during a request, the :data:`request` and :data:`session` proxies11are accessed instead.

Merge remote-tracking branch 'upstream/0.12-maintenance'Adrian Moennichbefore adoptioneb1c2fa

line 12why, one step back
12

Merge pull request #2685 from davidism/app-context-docsDavid Lordbefore adoption16d83d6

lines 13–15why, one step back
13This is similar to the :doc:`/appcontext`, which keeps track of the
14application-level data independent of a request. A corresponding15application context is pushed when a request context is pushed.

Merge remote-tracking branch 'upstream/0.12-maintenance'Adrian Moennichbefore adoptioneb1c2fa

lines 16–17why, one step back
16
17

Merge pull request #2685 from davidism/app-context-docsDavid Lordbefore adoption16d83d6

lines 18–19why, one step back
18Purpose of the Context
19----------------------

Merge remote-tracking branch 'upstream/0.12-maintenance'Adrian Moennichbefore adoptioneb1c2fa

line 20why, one step back
20

Merge pull request #2685 from davidism/app-context-docsDavid Lordbefore adoption16d83d6

lines 21–26why, one step back
21When the :class:`Flask` application handles a request, it creates a
22:class:`Request` object based on the environment it received from the23WSGI server. Because a *worker* (thread, process, or coroutine depending24on the server) handles only one request at a time, the request data can25be considered global to that worker during that request. Flask uses the26term *context local* for this.

Merge remote-tracking branch 'upstream/0.12-maintenance'Adrian Moennichbefore adoptioneb1c2fa

line 27why, one step back
27

Merge pull request #2685 from davidism/app-context-docsDavid Lordbefore adoption16d83d6

lines 28–31why, one step back
28Flask automatically *pushes* a request context when handling a request.
29View functions, error handlers, and other functions that run during a30request will have access to the :data:`request` proxy, which points to31the request object for the current request.

Merge remote-tracking branch 'upstream/0.12-maintenance'Adrian Moennichbefore adoptioneb1c2fa

lines 32–33why, one step back
32
33

Merge pull request #2685 from davidism/app-context-docsDavid Lordbefore adoption16d83d6

lines 34–35why, one step back
34Lifetime of the Context
35-----------------------

Merge remote-tracking branch 'upstream/0.12-maintenance'Adrian Moennichbefore adoptioneb1c2fa

line 36why, one step back
36

Merge pull request #2685 from davidism/app-context-docsDavid Lordbefore adoption16d83d6

lines 37–39why, one step back
37When a Flask application begins handling a request, it pushes a request
38context, which also pushes an :doc:`/appcontext`. When the request ends39it pops the request context then the application context.

Merge remote-tracking branch 'upstream/0.12-maintenance'Adrian Moennichbefore adoptioneb1c2fa

line 40why, one step back
40

Merge pull request #2685 from davidism/app-context-docsDavid Lordbefore adoption16d83d6

lines 41–44why, one step back
41The context is unique to each thread (or other worker type).
42:data:`request` cannot be passed to another thread, the other thread43will have a different context stack and will not know about the request44the parent thread was pointing to.

Merge remote-tracking branch 'upstream/0.12-maintenance'Adrian Moennichbefore adoptioneb1c2fa

line 45why, one step back
45

Merge pull request #2685 from davidism/app-context-docsDavid Lordbefore adoption16d83d6

lines 46–47why, one step back
46Context locals are implemented in Werkzeug. See :doc:`werkzeug:local`
47for more information on how this works internally.

Merge remote-tracking branch 'upstream/0.12-maintenance'Adrian Moennichbefore adoptioneb1c2fa

lines 48–49why, one step back
48
49

Merge pull request #2685 from davidism/app-context-docsDavid Lordbefore adoption16d83d6

lines 50–51why, one step back
50Manually Push a Context
51-----------------------

Merge remote-tracking branch 'upstream/0.12-maintenance'Adrian Moennichbefore adoptioneb1c2fa

line 52why, one step back
52

Merge pull request #2685 from davidism/app-context-docsDavid Lordbefore adoption16d83d6

lines 53–54why, one step back
53If you try to access :data:`request`, or anything that uses it, outside
54a request context, you'll get this error message:

Merge remote-tracking branch 'upstream/0.12-maintenance'Adrian Moennichbefore adoptioneb1c2fa

line 55why, one step back
55

Merge pull request #2685 from davidism/app-context-docsDavid Lordbefore adoption16d83d6

line 56why, one step back
56.. code-block:: pytb

Merge remote-tracking branch 'upstream/0.12-maintenance'Adrian Moennichbefore adoptioneb1c2fa

line 57why, one step back
57

Merge pull request #2685 from davidism/app-context-docsDavid Lordbefore adoption16d83d6

line 58why, one step back
58 RuntimeError: Working outside of request context.

Merge remote-tracking branch 'upstream/0.12-maintenance'Adrian Moennichbefore adoptioneb1c2fa

line 59why, one step back
59

Merge pull request #2685 from davidism/app-context-docsDavid Lordbefore adoption16d83d6

lines 60–62why, one step back
60 This typically means that you attempted to use functionality that
61 needed an active HTTP request. Consult the documentation on testing62 for information about how to avoid this problem.

Merge remote-tracking branch 'upstream/0.12-maintenance'Adrian Moennichbefore adoptioneb1c2fa

line 63why, one step back
63

Merge pull request #2685 from davidism/app-context-docsDavid Lordbefore adoption16d83d6

lines 64–69why, one step back
64This should typically only happen when testing code that expects an
65active 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. ::

Merge remote-tracking branch 'upstream/0.12-maintenance'Adrian Moennichbefore adoptioneb1c2fa

line 70why, one step back
70

Merge pull request #2685 from davidism/app-context-docsDavid Lordbefore adoption16d83d6

lines 71–86why, one step back
71 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`.8586

Merge remote-tracking branch 'upstream/0.12-maintenance'Adrian Moennichbefore adoptioneb1c2fa

lines 87–89why, one step back
87How the Context Works
88---------------------89

Merge pull request #2685 from davidism/app-context-docsDavid Lordbefore adoption16d83d6

lines 90–95why, one step back
90The :meth:`Flask.wsgi_app` method is called to handle each request. It
91manages the contexts during the request. Internally, the request and92application contexts work as stacks, :data:`_request_ctx_stack` and93:data:`_app_ctx_stack`. When contexts are pushed onto the stack, the94proxies that depend on them are available and point at information from95the top context on the stack.

Merge remote-tracking branch 'upstream/0.12-maintenance'Adrian Moennichbefore adoptioneb1c2fa

line 96why, one step back
96

Merge pull request #2685 from davidism/app-context-docsDavid Lordbefore adoption16d83d6

lines 97–102why, one step back
97When the request starts, a :class:`~ctx.RequestContext` is created and
98pushed, 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.

Merge remote-tracking branch 'upstream/0.12-maintenance'Adrian Moennichbefore adoptioneb1c2fa

line 103why, one step back
103

Merge pull request #2685 from davidism/app-context-docsDavid Lordbefore adoption16d83d6

lines 104–107why, one step back
104Because the contexts are stacks, other contexts may be pushed to change
105the proxies during a request. While this is not a common pattern, it106can be used in advanced applications to, for example, do internal107redirects or chain different applications together.

Merge remote-tracking branch 'upstream/0.12-maintenance'Adrian Moennichbefore adoptioneb1c2fa

line 108why, one step back
108

Merge pull request #2685 from davidism/app-context-docsDavid Lordbefore adoption16d83d6

lines 109–113why, one step back
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 are executed. These113execute even if an unhandled exception occurred during dispatch.

Merge remote-tracking branch 'upstream/0.12-maintenance'Adrian Moennichbefore adoptioneb1c2fa

lines 114–120why, one step back
114
115116.. _callbacks-and-errors:117118Callbacks and Errors119--------------------120

Merge pull request #2685 from davidism/app-context-docsDavid Lordbefore adoption16d83d6

lines 121–123why, one step back
121Flask dispatches a request in multiple stages which can affect the
122request, response, and how errors are handled. The contexts are active123during all of these stages.

Merge remote-tracking branch 'upstream/0.12-maintenance'Adrian Moennichbefore adoptioneb1c2fa

line 124why, one step back
124

Merge pull request #2685 from davidism/app-context-docsDavid Lordbefore adoption16d83d6

lines 125–127why, one step back
125A :class:`Blueprint` can add handlers for these events that are specific
126to the blueprint. The handlers for a blueprint will run if the blueprint127owns the route that matches the request.

Merge remote-tracking branch 'upstream/0.12-maintenance'Adrian Moennichbefore adoptioneb1c2fa

line 128why, one step back
128

Merge pull request #2685 from davidism/app-context-docsDavid Lordbefore adoption16d83d6

lines 129–132why, one step back
129#. Before each request, :meth:`~Flask.before_request` functions are
130 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.

Merge remote-tracking branch 'upstream/0.12-maintenance'Adrian Moennichbefore adoptioneb1c2fa

line 133why, one step back
133

Merge pull request #2685 from davidism/app-context-docsDavid Lordbefore adoption16d83d6

lines 134–136why, one step back
134#. If the :meth:`~Flask.before_request` functions did not return a
135 response, the view function for the matched route is called and136 returns a response.

Merge remote-tracking branch 'upstream/0.12-maintenance'Adrian Moennichbefore adoptioneb1c2fa

line 137why, one step back
137

Merge pull request #2685 from davidism/app-context-docsDavid Lordbefore adoption16d83d6

lines 138–140why, one step back
138#. The return value of the view is converted into an actual response
139 object and passed to the :meth:`~Flask.after_request`140 functions. Each function returns a modified or new response object.

Merge remote-tracking branch 'upstream/0.12-maintenance'Adrian Moennichbefore adoptioneb1c2fa

line 141why, one step back
141

Merge pull request #2685 from davidism/app-context-docsDavid Lordbefore adoption16d83d6

lines 142–145why, one step back
142#. After the response is returned, the contexts are popped, which calls
143 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.

Merge remote-tracking branch 'upstream/0.12-maintenance'Adrian Moennichbefore adoptioneb1c2fa

line 146why, one step back
146

Merge pull request #2685 from davidism/app-context-docsDavid Lordbefore adoption16d83d6

lines 147–152why, one step back
147If an exception is raised before the teardown functions, Flask tries to
148match 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.

Merge remote-tracking branch 'upstream/0.12-maintenance'Adrian Moennichbefore adoptioneb1c2fa

line 153why, one step back
153

Merge pull request #2685 from davidism/app-context-docsDavid Lordbefore adoption16d83d6

lines 154–157why, one step back
154If debug mode is enabled, unhandled exceptions are not converted to a
155``500`` response and instead are propagated to the WSGI server. This156allows the development server to present the interactive debugger with157the traceback.

Merge remote-tracking branch 'upstream/0.12-maintenance'Adrian Moennichbefore adoptioneb1c2fa

line 158why, one step back
158

Merge pull request #2685 from davidism/app-context-docsDavid Lordbefore adoption16d83d6

line 159why, one step back
159

Merge remote-tracking branch 'upstream/0.12-maintenance'Adrian Moennichbefore adoptioneb1c2fa

line 160why, one step back
160Teardown Callbacks

Merge pull request #2685 from davidism/app-context-docsDavid Lordbefore adoption16d83d6

line 161why, one step back
161~~~~~~~~~~~~~~~~~~

Merge remote-tracking branch 'upstream/0.12-maintenance'Adrian Moennichbefore adoptioneb1c2fa

line 162why, one step back
162

Merge pull request #2685 from davidism/app-context-docsDavid Lordbefore adoption16d83d6

lines 163–169why, one step back
163The teardown callbacks are independent of the request dispatch, and are
164instead 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.

Merge remote-tracking branch 'upstream/0.12-maintenance'Adrian Moennichbefore adoptioneb1c2fa

line 170why, one step back
170

Merge pull request #2685 from davidism/app-context-docsDavid Lordbefore adoption16d83d6

lines 171–174why, one step back
171During testing, it can be useful to defer popping the contexts after the
172request ends, so that their data can be accessed in the test function.173Using the :meth:`~Flask.test_client` as a ``with`` block to preserve the174contexts until the with block exits.

Merge remote-tracking branch 'upstream/0.12-maintenance'Adrian Moennichbefore adoptioneb1c2fa

line 175why, one step back
175

Merge pull request #2685 from davidism/app-context-docsDavid Lordbefore adoption16d83d6

line 176why, one step back
176.. code-block:: python

Merge remote-tracking branch 'upstream/0.12-maintenance'Adrian Moennichbefore adoptioneb1c2fa

line 177why, one step back
177

Merge pull request #2685 from davidism/app-context-docsDavid Lordbefore adoption16d83d6

line 178why, one step back
178 from flask import Flask, request

Merge remote-tracking branch 'upstream/0.12-maintenance'Adrian Moennichbefore adoptioneb1c2fa

line 179why, one step back
179

Merge pull request #2685 from davidism/app-context-docsDavid Lordbefore adoption16d83d6

line 180why, one step back
180 app = Flask(__name__)

Merge remote-tracking branch 'upstream/0.12-maintenance'Adrian Moennichbefore adoptioneb1c2fa

line 181why, one step back
181

Merge pull request #2685 from davidism/app-context-docsDavid Lordbefore adoption16d83d6

lines 182–185why, one step back
182 @app.route('/')
183 def hello():184 print('during view')185 return 'Hello, World!'

Merge remote-tracking branch 'upstream/0.12-maintenance'Adrian Moennichbefore adoptioneb1c2fa

line 186why, one step back
186

Merge pull request #2685 from davidism/app-context-docsDavid Lordbefore adoption16d83d6

lines 187–189why, one step back
187 @app.teardown_request
188 def show_teardown(exception):189 print('after with block')

Merge remote-tracking branch 'upstream/0.12-maintenance'Adrian Moennichbefore adoptioneb1c2fa

line 190why, one step back
190

Merge pull request #2685 from davidism/app-context-docsDavid Lordbefore adoption16d83d6

lines 191–195why, one step back
191 with app.test_request_context():
192 print('during with block')193194 # teardown functions are called after the context with block exits195

doc reqcontext fix teardown example (#2892)Alexis Benoistbefore adoptionb9b88b0

line 196why, one step back
196 with app.test_client() as client:

Merge pull request #2685 from davidism/app-context-docsDavid Lordbefore adoption16d83d6

lines 197–242why, one step back
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 exists203204Signals205~~~~~~~206207If :data:`~signals.signals_available` is true, the following signals are208sent:209210#. :data:`request_started` is sent before the211 :meth:`~Flask.before_request` functions are called.212213#. :data:`request_finished` is sent after the214 :meth:`~Flask.after_request` functions are called.215216#. :data:`got_request_exception` is sent when an exception begins to217 be handled, but before an :meth:`~Flask.errorhandler` is looked up or218 called.219220#. :data:`request_tearing_down` is sent after the221 :meth:`~Flask.teardown_request` functions are called.222223224Context Preservation on Error225-----------------------------226227At the end of a request, the request context is popped and all data228associated with it is destroyed. If an error occurs during development,229it is useful to delay destroying the data for debugging purposes.230231When the development server is running in development mode (the232``FLASK_ENV`` environment variable is set to ``'development'``), the233error and data will be preserved and shown in the interactive debugger.234235This behavior can be controlled with the236:data:`PRESERVE_CONTEXT_ON_EXCEPTION` config. As described above, it237defaults to ``True`` in the development environment.238239Do not enable :data:`PRESERVE_CONTEXT_ON_EXCEPTION` in production, as it240will cause your application to leak memory on exceptions.241242

Merge remote-tracking branch 'upstream/0.12-maintenance'Adrian Moennichbefore adoptioneb1c2fa

lines 243–247why, one step back
243.. _notes-on-proxies:
244245Notes On Proxies246----------------247

Merge pull request #2685 from davidism/app-context-docsDavid Lordbefore adoption16d83d6

lines 248–251why, one step back
248Some of the objects provided by Flask are proxies to other objects. The
249proxies are accessed in the same way for each worker thread, but250point to the unique object bound to each worker behind the scenes as251described on this page.

Merge remote-tracking branch 'upstream/0.12-maintenance'Adrian Moennichbefore adoptioneb1c2fa

lines 252–255why, one step back
252
253Most of the time you don't have to care about that, but there are some254exceptions where it is good to know that this object is an actual proxy:255

Merge pull request #2685 from davidism/app-context-docsDavid Lordbefore adoption16d83d6

lines 256–260why, one step back
256- The proxy objects cannot fake their type as the actual object types.
257 If you want to perform instance checks, you have to do that on the258 object being proxied.259- If the specific object reference is important, for example for260 sending :ref:`signals` or passing data to a background thread.

Merge remote-tracking branch 'upstream/0.12-maintenance'Adrian Moennichbefore adoptioneb1c2fa

line 261why, one step back
261

Merge pull request #2685 from davidism/app-context-docsDavid Lordbefore adoption16d83d6

lines 262–263why, one step back
262If you need to access the underlying object that is proxied, use the
263:meth:`~werkzeug.local.LocalProxy._get_current_object` method::

Merge remote-tracking branch 'upstream/0.12-maintenance'Adrian Moennichbefore adoptioneb1c2fa

lines 264–266why, one step back
264
265 app = current_app._get_current_object()266 my_signal.send(app)