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 fileTake 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 back1The App and Request Context2===========================Merge branch '2.2.x'David Lordbefore adoption73739a2
line 3why, one step back3merge app and request context (#5812)David Lordbefore adoptionadf3636
lines 4–7why, one step back4The context keeps track of data and objects during a request, CLI command, or5other 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 back8merge app and request context (#5812)David Lordbefore adoptionadf3636
lines 9–13why, one step back9When 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 back141516Purpose of the Context17----------------------18merge app and request context (#5812)David Lordbefore adoptionadf3636
lines 19–20why, one step back19The context and proxies help solve two development issues: circular imports, and20passing around global data during a request.Merge branch '2.2.x'David Lordbefore adoption73739a2
line 21why, one step back21merge app and request context (#5812)David Lordbefore adoptionadf3636
lines 22–28why, one step back22The :class:`.Flask` application object has attributes, such as23: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 back29merge app and request context (#5812)David Lordbefore adoptionadf3636
lines 30–33why, one step back30When 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 back34merge app and request context (#5812)David Lordbefore adoptionadf3636
lines 35–39why, one step back35Flask solves these issues with the *active context* pattern. Rather than36importing 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 back4041merge app and request context (#5812)David Lordbefore adoptionadf3636
lines 42–43why, one step back42Context During Setup43--------------------Merge branch '2.2.x'David Lordbefore adoption73739a2
line 44why, one step back44merge app and request context (#5812)David Lordbefore adoptionadf3636
lines 45–46why, one step back45If 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 back4748.. code-block:: pytb4950 RuntimeError: Working outside of application context.51merge app and request context (#5812)David Lordbefore adoptionadf3636
lines 52–54why, one step back52 Attempted to use functionality that expected a current application to be53 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 back5556If you see that error while configuring your application, such as whenmerge app and request context (#5812)David Lordbefore adoptionadf3636
lines 57–58why, one step back57initializing an extension, you can push a context manually since you have direct58access to the ``app``. Use :meth:`.Flask.app_context` in a ``with`` block.Merge branch '2.2.x'David Lordbefore adoption73739a2
line 59why, one step back59merge app and request context (#5812)David Lordbefore adoptionadf3636
lines 60–61why, one step back60.. code-block:: python61Merge branch '2.2.x'David Lordbefore adoption73739a2
lines 62–69why, one step back62 def create_app():63 app = Flask(__name__)6465 with app.app_context():66 init_db()6768 return app69merge app and request context (#5812)David Lordbefore adoptionadf3636
lines 70–72why, one step back70If you see that error somewhere else in your code not related to setting up the71application, 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 back7374merge app and request context (#5812)David Lordbefore adoptionadf3636
lines 75–76why, one step back75Context During Testing76----------------------Merge branch '2.2.x'David Lordbefore adoption73739a2
line 77why, one step back77merge app and request context (#5812)David Lordbefore adoptionadf3636
lines 78–79why, one step back78See :doc:`/testing` for detailed information about managing the context during79tests.Merge branch '2.2.x'David Lordbefore adoption73739a2
line 80why, one step back80merge app and request context (#5812)David Lordbefore adoptionadf3636
lines 81–82why, one step back81If you try to access :data:`.request`, :data:`.session`, or anything that uses82it, outside a request context, you'll get this error message:Merge branch '2.2.x'David Lordbefore adoption73739a2
line 83why, one step back83merge app and request context (#5812)David Lordbefore adoptionadf3636
line 84why, one step back84.. code-block:: pytbMerge branch '2.2.x'David Lordbefore adoption73739a2
line 85why, one step back85merge app and request context (#5812)David Lordbefore adoptionadf3636
line 86why, one step back86 RuntimeError: Working outside of request context.Merge branch '2.2.x'David Lordbefore adoption73739a2
line 87why, one step back87merge app and request context (#5812)David Lordbefore adoptionadf3636
lines 88–89why, one step back88 Attempted to use functionality that expected an active HTTP request. See the89 documentation on request context for more information.Merge branch '2.2.x'David Lordbefore adoption73739a2
line 90why, one step back90merge app and request context (#5812)David Lordbefore adoptionadf3636
lines 91–93why, one step back91This will probably only happen during tests. If you see that error somewhere92else 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 back94merge app and request context (#5812)David Lordbefore adoptionadf3636
lines 95–96why, one step back95The primary way to solve this is to use :meth:`.Flask.test_client` to simulate96a full request.Merge branch '2.2.x'David Lordbefore adoption73739a2
line 97why, one step back97merge app and request context (#5812)David Lordbefore adoptionadf3636
lines 98–99why, one step back98If you only want to unit test one function, rather than a full request, use99:meth:`.Flask.test_request_context` in a ``with`` block.Merge branch '2.2.x'David Lordbefore adoption73739a2
line 100why, one step back100merge app and request context (#5812)David Lordbefore adoptionadf3636
line 101why, one step back101.. code-block:: pythonMerge branch '2.2.x'David Lordbefore adoption73739a2
line 102why, one step back102merge app and request context (#5812)David Lordbefore adoptionadf3636
lines 103–105why, one step back103 def generate_report(year):104 format = request.args.get("format")105 ...Merge branch '2.2.x'David Lordbefore adoption73739a2
line 106why, one step back106merge app and request context (#5812)David Lordbefore adoptionadf3636
lines 107–110why, one step back107 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 back111112merge app and request context (#5812)David Lordbefore adoptionadf3636
line 113why, one step back113.. _context-visibility:Merge branch '2.2.x'David Lordbefore adoption73739a2
line 114why, one step back114merge app and request context (#5812)David Lordbefore adoptionadf3636
lines 115–116why, one step back115Visibility of the Context116-------------------------Merge branch '2.2.x'David Lordbefore adoption73739a2
line 117why, one step back117merge app and request context (#5812)David Lordbefore adoptionadf3636
lines 118–120why, one step back118The context will have the same lifetime as an activity, such as a request, CLI119command, 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 back121fix codespell findingsDavid Lordbefore adoption9b74a90
line 122why, one step back122When a Flask application handles a request, it pushes a request contextmerge app and request context (#5812)David Lordbefore adoptionadf3636
lines 123–127why, one step back123to 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 back128merge app and request context (#5812)David Lordbefore adoptionadf3636
lines 129–131why, one step back129The context is unique to each thread (or other worker type). The proxies cannot130be 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 back132merge app and request context (#5812)David Lordbefore adoptionadf3636
lines 133–143why, one step back133Besides being scoped to each worker, the proxy object has a separate type and134identity 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)142143Docs typo/markup fixes (#5829)Hynek Schlawackbefore adoption88a65bb
lines 144–145why, one step back144Lifecycle of the Context145------------------------merge app and request context (#5812)David Lordbefore adoptionadf3636
lines 146–165why, one step back146147Flask 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 theseall teardown callbacks are called despite errors (#5928)David Lordbefore adoptionc34d6e8
lines 166–167why, one step back166functions in a way that does not depend on other callbacks. All callbacks are167called even if any raise an error.merge app and request context (#5812)David Lordbefore adoptionadf3636
lines 168–187why, one step back168169170How 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.