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
1The App and Request Context2===========================34The 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.89When 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.141516Purpose of the Context17----------------------1819The context and proxies help solve two development issues: circular imports, and20passing around global data during a request.2122The :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.2930When 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.3435Flask 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.404142Context During Setup43--------------------4445If you try to access :data:`.current_app`, :data:`.g`, or anything that uses it,46outside an app context, you'll get this error message:4748.. code-block:: pytb4950 RuntimeError: Working outside of application context.5152 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.5556If you see that error while configuring your application, such as when57initializing an extension, you can push a context manually since you have direct58access to the ``app``. Use :meth:`.Flask.app_context` in a ``with`` block.5960.. code-block:: python6162 def create_app():63 app = Flask(__name__)6465 with app.app_context():66 init_db()6768 return app6970If 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.737475Context During Testing76----------------------7778See :doc:`/testing` for detailed information about managing the context during79tests.8081If you try to access :data:`.request`, :data:`.session`, or anything that uses82it, outside a request context, you'll get this error message:8384.. code-block:: pytb8586 RuntimeError: Working outside of request context.8788 Attempted to use functionality that expected an active HTTP request. See the89 documentation on request context for more information.9091This 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.9495The primary way to solve this is to use :meth:`.Flask.test_client` to simulate96a full request.9798If you only want to unit test one function, rather than a full request, use99:meth:`.Flask.test_request_context` in a ``with`` block.100101.. code-block:: python102103 def generate_report(year):104 format = request.args.get("format")105 ...106107 with app.test_request_context(108 "/make_report/2017", query_string={"format": "short"}109 ):110 generate_report()111112113.. _context-visibility:114115Visibility of the Context116-------------------------117118The 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.121122When a Flask application handles a request, it pushes a request context123to 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.128129The 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.132133Besides 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)142143144Lifecycle of the Context145------------------------146147Flask 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 these166functions in a way that does not depend on other callbacks. All callbacks are167called even if any raise an error.168169170How 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.