Skip to content
Myr

appcontext.rst

This file

Path

docs/appcontext.rst

147 lines · 5.0 KiB

Last changed by

Merge pull request #5058 from pallets/require-blinkerDavid Lordbefore adoptiona05c0c6

History of this file

Take it

1.. currentmodule:: flask23The Application Context4=======================56The application context keeps track of the application-level data during7a request, CLI command, or other activity. Rather than passing the8application around to each function, the :data:`current_app` and9:data:`g` proxies are accessed instead.1011This is similar to :doc:`/reqcontext`, which keeps track of12request-level data during a request. A corresponding application context13is pushed when a request context is pushed.1415Purpose of the Context16----------------------1718The :class:`Flask` application object has attributes, such as19:attr:`~Flask.config`, that are useful to access within views and20:doc:`CLI commands </cli>`. However, importing the ``app`` instance21within the modules in your project is prone to circular import issues.22When using the :doc:`app factory pattern </patterns/appfactories>` or23writing reusable :doc:`blueprints </blueprints>` or24:doc:`extensions </extensions>` there won't be an ``app`` instance to25import at all.2627Flask solves this issue with the *application context*. Rather than28referring to an ``app`` directly, you use the :data:`current_app`29proxy, which points to the application handling the current activity.3031Flask automatically *pushes* an application context when handling a32request. View functions, error handlers, and other functions that run33during a request will have access to :data:`current_app`.3435Flask will also automatically push an app context when running CLI36commands registered with :attr:`Flask.cli` using ``@app.cli.command()``.373839Lifetime of the Context40-----------------------4142The application context is created and destroyed as necessary. When a43Flask application begins handling a request, it pushes an application44context and a :doc:`request context </reqcontext>`. When the request45ends it pops the request context then the application context.46Typically, an application context will have the same lifetime as a47request.4849See :doc:`/reqcontext` for more information about how the contexts work50and the full life cycle of a request.515253Manually Push a Context54-----------------------5556If you try to access :data:`current_app`, or anything that uses it,57outside an application context, you'll get this error message:5859.. code-block:: pytb6061    RuntimeError: Working outside of application context.6263    This typically means that you attempted to use functionality that64    needed to interface with the current application object in some way.65    To solve this, set up an application context with app.app_context().6667If you see that error while configuring your application, such as when68initializing an extension, you can push a context manually since you69have direct access to the ``app``. Use :meth:`~Flask.app_context` in a70``with`` block, and everything that runs in the block will have access71to :data:`current_app`. ::7273    def create_app():74        app = Flask(__name__)7576        with app.app_context():77            init_db()7879        return app8081If you see that error somewhere else in your code not related to82configuring the application, it most likely indicates that you should83move that code into a view function or CLI command.848586Storing Data87------------8889The application context is a good place to store common data during a90request or CLI command. Flask provides the :data:`g object <g>` for this91purpose. It is a simple namespace object that has the same lifetime as92an application context.9394.. note::95    The ``g`` name stands for "global", but that is referring to the96    data being global *within a context*. The data on ``g`` is lost97    after the context ends, and it is not an appropriate place to store98    data between requests. Use the :data:`session` or a database to99    store data across requests.100101A common use for :data:`g` is to manage resources during a request.1021031.  ``get_X()`` creates resource ``X`` if it does not exist, caching it104    as ``g.X``.1052.  ``teardown_X()`` closes or otherwise deallocates the resource if it106    exists. It is registered as a :meth:`~Flask.teardown_appcontext`107    handler.108109For example, you can manage a database connection using this pattern::110111    from flask import g112113    def get_db():114        if 'db' not in g:115            g.db = connect_to_database()116117        return g.db118119    @app.teardown_appcontext120    def teardown_db(exception):121        db = g.pop('db', None)122123        if db is not None:124            db.close()125126During a request, every call to ``get_db()`` will return the same127connection, and it will be closed automatically at the end of the128request.129130You can use :class:`~werkzeug.local.LocalProxy` to make a new context131local from ``get_db()``::132133    from werkzeug.local import LocalProxy134    db = LocalProxy(get_db)135136Accessing ``db`` will call ``get_db`` internally, in the same way that137:data:`current_app` works.138139140Events and Signals141------------------142143The application will call functions registered with :meth:`~Flask.teardown_appcontext`144when the application context is popped.145146The following signals are sent: :data:`appcontext_pushed`,147:data:`appcontext_tearing_down`, and :data:`appcontext_popped`.