appcontext.rst
This file
Path
docs/appcontext.rst
159 lines · 5.4 KiB
Last changed by
Merge pull request #3199 from alecbrooks/masterDavid Lordbefore adoptionded0f68
History of this fileTake it
1.. currentmodule:: flask23.. _app-context:45The Application Context6=======================78The application context keeps track of the application-level data during9a request, CLI command, or other activity. Rather than passing the10application around to each function, the :data:`current_app` and11:data:`g` proxies are accessed instead.1213This is similar to the :doc:`/reqcontext`, which keeps track of14request-level data during a request. A corresponding application context15is pushed when a request context is pushed.1617Purpose of the Context18----------------------1920The :class:`Flask` application object has attributes, such as21:attr:`~Flask.config`, that are useful to access within views and22:doc:`CLI commands </cli>`. However, importing the ``app`` instance23within the modules in your project is prone to circular import issues.24When using the :doc:`app factory pattern </patterns/appfactories>` or25writing reusable :doc:`blueprints </blueprints>` or26:doc:`extensions </extensions>` there won't be an ``app`` instance to27import at all.2829Flask solves this issue with the *application context*. Rather than30referring to an ``app`` directly, you use the the :data:`current_app`31proxy, which points to the application handling the current activity.3233Flask automatically *pushes* an application context when handling a34request. View functions, error handlers, and other functions that run35during a request will have access to :data:`current_app`.3637Flask will also automatically push an app context when running CLI38commands registered with :attr:`Flask.cli` using ``@app.cli.command()``.394041Lifetime of the Context42-----------------------4344The application context is created and destroyed as necessary. When a45Flask application begins handling a request, it pushes an application46context and a :doc:`request context </reqcontext>`. When the request47ends it pops the request context then the application context.48Typically, an application context will have the same lifetime as a49request.5051See :doc:`/reqcontext` for more information about how the contexts work52and the full life cycle of a request.535455Manually Push a Context56-----------------------5758If you try to access :data:`current_app`, or anything that uses it,59outside an application context, you'll get this error message:6061.. code-block:: pytb6263 RuntimeError: Working outside of application context.6465 This typically means that you attempted to use functionality that66 needed to interface with the current application object in some way.67 To solve this, set up an application context with app.app_context().6869If you see that error while configuring your application, such as when70initializing an extension, you can push a context manually since you71have direct access to the ``app``. Use :meth:`~Flask.app_context` in a72``with`` block, and everything that runs in the block will have access73to :data:`current_app`. ::7475 def create_app():76 app = Flask(__name__)7778 with app.app_context():79 init_db()8081 return app8283If you see that error somewhere else in your code not related to84configuring the application, it most likely indicates that you should85move that code into a view function or CLI command.868788Storing Data89------------9091The application context is a good place to store common data during a92request or CLI command. Flask provides the :data:`g object <g>` for this93purpose. It is a simple namespace object that has the same lifetime as94an application context.9596.. note::97 The ``g`` name stands for "global", but that is referring to the98 data being global *within a context*. The data on ``g`` is lost99 after the context ends, and it is not an appropriate place to store100 data between requests. Use the :data:`session` or a database to101 store data across requests.102103A common use for :data:`g` is to manage resources during a request.1041051. ``get_X()`` creates resource ``X`` if it does not exist, caching it106 as ``g.X``.1072. ``teardown_X()`` closes or otherwise deallocates the resource if it108 exists. It is registered as a :meth:`~Flask.teardown_appcontext`109 handler.110111For example, you can manage a database connection using this pattern::112113 from flask import g114115 def get_db():116 if 'db' not in g:117 g.db = connect_to_database()118119 return g.db120121 @app.teardown_appcontext122 def teardown_db():123 db = g.pop('db', None)124125 if db is not None:126 db.close()127128During a request, every call to ``get_db()`` will return the same129connection, and it will be closed automatically at the end of the130request.131132You can use :class:`~werkzeug.local.LocalProxy` to make a new context133local from ``get_db()``::134135 from werkzeug.local import LocalProxy136 db = LocalProxy(get_db)137138Accessing ``db`` will call ``get_db`` internally, in the same way that139:data:`current_app` works.140141----142143If you're writing an extension, :data:`g` should be reserved for user144code. You may store internal data on the context itself, but be sure to145use a sufficiently unique name. The current context is accessed with146:data:`_app_ctx_stack.top <_app_ctx_stack>`. For more information see147:doc:`extensiondev`.148149150Events and Signals151------------------152153The application will call functions registered with154:meth:`~Flask.teardown_appcontext` when the application context is155popped.156157If :data:`~signals.signals_available` is true, the following signals are158sent: :data:`appcontext_pushed`, :data:`appcontext_tearing_down`, and159:data:`appcontext_popped`.