Skip to content
Myr

appcontext.rst

This file

Path

docs/appcontext.rst

187 lines · 7.5 KiB

Last changed by

all teardown callbacks are called despite errors (#5928)David Lordbefore adoptionc34d6e8

History of this file

Take it

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

merge app and request context (#5812)David Lordbefore adoptionadf3636

lines 1–2why, one step back
1The App and Request Context
2===========================

Merge branch '2.2.x'David Lordbefore adoption73739a2

line 3why, one step back
3

merge app and request context (#5812)David Lordbefore adoptionadf3636

lines 4–7why, one step back
4The context keeps track of data and objects during a request, CLI command, or
5other activity. Rather than passing this data around to every function, the6:data:`.current_app`, :data:`.g`, :data:`.request`, and :data:`.session` proxies7are accessed instead.

Merge branch '2.2.x'David Lordbefore adoption73739a2

line 8why, one step back
8

merge app and request context (#5812)David Lordbefore adoptionadf3636

lines 9–13why, one step back
9When handling a request, the context is referred to as the "request context"
10because it contains request data in addition to application data. Otherwise,11such as during a CLI command, it is referred to as the "app context". During an12app context, :data:`.current_app` and :data:`.g` are available, while during a13request context :data:`.request` and :data:`.session` are also available.

Merge branch '2.2.x'David Lordbefore adoption73739a2

lines 14–18why, one step back
14
1516Purpose of the Context17----------------------18

merge app and request context (#5812)David Lordbefore adoptionadf3636

lines 19–20why, one step back
19The context and proxies help solve two development issues: circular imports, and
20passing around global data during a request.

Merge branch '2.2.x'David Lordbefore adoption73739a2

line 21why, one step back
21

merge app and request context (#5812)David Lordbefore adoptionadf3636

lines 22–28why, one step back
22The :class:`.Flask` application object has attributes, such as
23:attr:`~.Flask.config`, that are useful to access within views and other24functions. However, importing the ``app`` instance within the modules in your25project is prone to circular import issues. When using the26:doc:`app factory pattern </patterns/appfactories>` or writing reusable27:doc:`blueprints </blueprints>` or :doc:`extensions </extensions>` there won't28be an ``app`` instance to import at all.

Merge branch '2.2.x'David Lordbefore adoption73739a2

line 29why, one step back
29

merge app and request context (#5812)David Lordbefore adoptionadf3636

lines 30–33why, one step back
30When the application handles a request, it creates a :class:`.Request` object.
31Because a *worker* handles only one request at a time, the request data can be32considered global to that worker during that request. Passing it as an argument33through every function during the request becomes verbose and redundant.

Merge branch '2.2.x'David Lordbefore adoption73739a2

line 34why, one step back
34

merge app and request context (#5812)David Lordbefore adoptionadf3636

lines 35–39why, one step back
35Flask solves these issues with the *active context* pattern. Rather than
36importing an ``app`` directly, or having to pass it and the request through to37every single function, you import and access the proxies, which point to the38currently active application and request data. This is sometimes referred to39as "context local" data.

Merge branch '2.2.x'David Lordbefore adoption73739a2

lines 40–41why, one step back
40
41

merge app and request context (#5812)David Lordbefore adoptionadf3636

lines 42–43why, one step back
42Context During Setup
43--------------------

Merge branch '2.2.x'David Lordbefore adoption73739a2

line 44why, one step back
44

merge app and request context (#5812)David Lordbefore adoptionadf3636

lines 45–46why, one step back
45If you try to access :data:`.current_app`, :data:`.g`, or anything that uses it,
46outside an app context, you'll get this error message:

Merge branch '2.2.x'David Lordbefore adoption73739a2

lines 47–51why, one step back
47
48.. code-block:: pytb4950 RuntimeError: Working outside of application context.51

merge app and request context (#5812)David Lordbefore adoptionadf3636

lines 52–54why, one step back
52 Attempted to use functionality that expected a current application to be
53 set. To solve this, set up an app context using 'with app.app_context()'.54 See the documentation on app context for more information.

Merge branch '2.2.x'David Lordbefore adoption73739a2

lines 55–56why, one step back
55
56If you see that error while configuring your application, such as when

merge app and request context (#5812)David Lordbefore adoptionadf3636

lines 57–58why, one step back
57initializing an extension, you can push a context manually since you have direct
58access to the ``app``. Use :meth:`.Flask.app_context` in a ``with`` block.

Merge branch '2.2.x'David Lordbefore adoption73739a2

line 59why, one step back
59

merge app and request context (#5812)David Lordbefore adoptionadf3636

lines 60–61why, one step back
60.. code-block:: python
61

Merge branch '2.2.x'David Lordbefore adoption73739a2

lines 62–69why, one step back
62 def create_app():
63 app = Flask(__name__)6465 with app.app_context():66 init_db()6768 return app69

merge app and request context (#5812)David Lordbefore adoptionadf3636

lines 70–72why, one step back
70If you see that error somewhere else in your code not related to setting up the
71application, it most likely indicates that you should move that code into a view72function or CLI command.

Merge branch '2.2.x'David Lordbefore adoption73739a2

lines 73–74why, one step back
73
74

merge app and request context (#5812)David Lordbefore adoptionadf3636

lines 75–76why, one step back
75Context During Testing
76----------------------

Merge branch '2.2.x'David Lordbefore adoption73739a2

line 77why, one step back
77

merge app and request context (#5812)David Lordbefore adoptionadf3636

lines 78–79why, one step back
78See :doc:`/testing` for detailed information about managing the context during
79tests.

Merge branch '2.2.x'David Lordbefore adoption73739a2

line 80why, one step back
80

merge app and request context (#5812)David Lordbefore adoptionadf3636

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

Merge branch '2.2.x'David Lordbefore adoption73739a2

line 83why, one step back
83

merge app and request context (#5812)David Lordbefore adoptionadf3636

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

Merge branch '2.2.x'David Lordbefore adoption73739a2

line 85why, one step back
85

merge app and request context (#5812)David Lordbefore adoptionadf3636

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

Merge branch '2.2.x'David Lordbefore adoption73739a2

line 87why, one step back
87

merge app and request context (#5812)David Lordbefore adoptionadf3636

lines 88–89why, one step back
88 Attempted to use functionality that expected an active HTTP request. See the
89 documentation on request context for more information.

Merge branch '2.2.x'David Lordbefore adoption73739a2

line 90why, one step back
90

merge app and request context (#5812)David Lordbefore adoptionadf3636

lines 91–93why, one step back
91This will probably only happen during tests. If you see that error somewhere
92else in your code not related to testing, it most likely indicates that you93should move that code into a view function.

Merge branch '2.2.x'David Lordbefore adoption73739a2

line 94why, one step back
94

merge app and request context (#5812)David Lordbefore adoptionadf3636

lines 95–96why, one step back
95The primary way to solve this is to use :meth:`.Flask.test_client` to simulate
96a full request.

Merge branch '2.2.x'David Lordbefore adoption73739a2

line 97why, one step back
97

merge app and request context (#5812)David Lordbefore adoptionadf3636

lines 98–99why, one step back
98If you only want to unit test one function, rather than a full request, use
99:meth:`.Flask.test_request_context` in a ``with`` block.

Merge branch '2.2.x'David Lordbefore adoption73739a2

line 100why, one step back
100

merge app and request context (#5812)David Lordbefore adoptionadf3636

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

Merge branch '2.2.x'David Lordbefore adoption73739a2

line 102why, one step back
102

merge app and request context (#5812)David Lordbefore adoptionadf3636

lines 103–105why, one step back
103 def generate_report(year):
104 format = request.args.get("format")105 ...

Merge branch '2.2.x'David Lordbefore adoption73739a2

line 106why, one step back
106

merge app and request context (#5812)David Lordbefore adoptionadf3636

lines 107–110why, one step back
107 with app.test_request_context(
108 "/make_report/2017", query_string={"format": "short"}109 ):110 generate_report()

Merge branch '2.2.x'David Lordbefore adoption73739a2

lines 111–112why, one step back
111
112

merge app and request context (#5812)David Lordbefore adoptionadf3636

line 113why, one step back
113.. _context-visibility:

Merge branch '2.2.x'David Lordbefore adoption73739a2

line 114why, one step back
114

merge app and request context (#5812)David Lordbefore adoptionadf3636

lines 115–116why, one step back
115Visibility of the Context
116-------------------------

Merge branch '2.2.x'David Lordbefore adoption73739a2

line 117why, one step back
117

merge app and request context (#5812)David Lordbefore adoptionadf3636

lines 118–120why, one step back
118The context will have the same lifetime as an activity, such as a request, CLI
119command, or ``with`` block. Various callbacks and signals registered with the120app will be run during the context.

Merge branch '2.2.x'David Lordbefore adoption73739a2

line 121why, one step back
121

fix codespell findingsDavid Lordbefore adoption9b74a90

line 122why, one step back
122When a Flask application handles a request, it pushes a request context

merge app and request context (#5812)David Lordbefore adoptionadf3636

lines 123–127why, one step back
123to set the active application and request data. When it handles a CLI command,
124it pushes an app context to set the active application. When the activity ends,125it pops that context. Proxy objects like :data:`.request`, :data:`.session`,126:data:`.g`, and :data:`.current_app`, are accessible while the context is pushed127and active, and are not accessible after the context is popped.

Merge branch '2.2.x'David Lordbefore adoption73739a2

line 128why, one step back
128

merge app and request context (#5812)David Lordbefore adoptionadf3636

lines 129–131why, one step back
129The context is unique to each thread (or other worker type). The proxies cannot
130be passed to another worker, which has a different context space and will not131know about the active context in the parent's space.

Merge branch '2.2.x'David Lordbefore adoption73739a2

line 132why, one step back
132

merge app and request context (#5812)David Lordbefore adoptionadf3636

lines 133–143why, one step back
133Besides being scoped to each worker, the proxy object has a separate type and
134identity than the proxied real object. In some cases you'll need access to the135real object, rather than the proxy. Use the136:meth:`~.LocalProxy._get_current_object` method in those cases.137138.. code-block:: python139140 app = current_app._get_current_object()141 my_signal.send(app)142143

Docs typo/markup fixes (#5829)Hynek Schlawackbefore adoption88a65bb

lines 144–145why, one step back
144Lifecycle of the Context
145------------------------

merge app and request context (#5812)David Lordbefore adoptionadf3636

lines 146–165why, one step back
146
147Flask dispatches a request in multiple stages which can affect the request,148response, and how errors are handled. See :doc:`/lifecycle` for a list of all149the steps, callbacks, and signals during each request. The following are the150steps directly related to the context.151152- The app context is pushed, the proxies are available.153- The :data:`.appcontext_pushed` signal is sent.154- The request is dispatched.155- Any :meth:`.Flask.teardown_request` decorated functions are called.156- The :data:`.request_tearing_down` signal is sent.157- Any :meth:`.Flask.teardown_appcontext` decorated functions are called.158- The :data:`.appcontext_tearing_down` signal is sent.159- The app context is popped, the proxies are no longer available.160- The :data:`.appcontext_popped` signal is sent.161162The teardown callbacks are called by the context when it is popped. They are163called even if there is an unhandled exception during dispatch. They may be164called multiple times in some test scenarios. This means there is no guarantee165that any other parts of the request dispatch have run. Be sure to write these

all teardown callbacks are called despite errors (#5928)David Lordbefore adoptionc34d6e8

lines 166–167why, one step back
166functions in a way that does not depend on other callbacks. All callbacks are
167called even if any raise an error.

merge app and request context (#5812)David Lordbefore adoptionadf3636

lines 168–187why, one step back
168
169170How the Context Works171---------------------172173Context locals are implemented using Python's :mod:`contextvars` and Werkzeug's174:class:`~werkzeug.local.LocalProxy`. Python's contextvars are a low level175structure to manage data local to a thread or coroutine. ``LocalProxy`` wraps176the contextvar so that access to any attributes and methods is forwarded to the177object stored in the contextvar.178179The context is tracked like a stack, with the active context at the top of the180stack. Flask manages pushing and popping contexts during requests, CLI commands,181testing, ``with`` blocks, etc. The proxies access attributes on the active182context.183184Because it is a stack, other contexts may be pushed to change the proxies during185an already active context. This is not a common pattern, but can be used in186advanced use cases. For example, a Flask application can be used as WSGI187middleware, calling another wrapped Flask app from a view.