Skip to content
Myr

appcontext.rst

This file

Path

docs/appcontext.rst

144 lines · 5.5 KiB

Last changed by

fix doc build errorDavid Lordbefore adoptiond2a46dc

History of this file

Take it

1.. _app-context:23The Application Context4=======================56.. versionadded:: 0.978One of the design ideas behind Flask is that there are at least two9different “states” in which code is executed:10111.  The application setup state, in which the application implicitly is12on the module level.1314    This state starts when the :class:`Flask` object is instantiated, and15    it implicitly ends when the first request comes in.  While the16    application is in this state, a few assumptions are true:1718    -   the programmer can modify the application object safely.19    -   no request handling happened so far20    -   you have to have a reference to the application object in order to21        modify it, there is no magic proxy that can give you a reference to22        the application object you're currently creating or modifying.23242.  In contrast, in the request handling state, a couple of other rules25exist:2627    -   while a request is active, the context local objects28        (:data:`flask.request` and others) point to the current request.29    -   any code can get hold of these objects at any time.30313.  There is also a third state somewhere in between 'module-level' and32'request-handling':3334    Sometimes you are dealing with an application in a way that is similar to35    how you interact with applications during request handling, but without36    there being an active request.  Consider, for instance, that you're37    sitting in an interactive Python shell and interacting with the38    application, or a command line application.3940The application context is what powers the :data:`~flask.current_app`41context local.4243Purpose of the Application Context44----------------------------------4546The main reason for the application's context existence is that in the47past a bunch of functionality was attached to the request context for lack48of a better solution.  Since one of the pillars of Flask's design is that49you can have more than one application in the same Python process.5051So how does the code find the “right” application?  In the past we52recommended passing applications around explicitly, but that caused issues53with libraries that were not designed with that in mind.5455A common workaround for that problem was to use the56:data:`~flask.current_app` proxy later on, which was bound to the current57request's application reference.  Since creating such a request context is58an unnecessarily expensive operation in case there is no request around,59the application context was introduced.6061Creating an Application Context62-------------------------------6364There are two ways to make an application context.  The first one is65implicit: whenever a request context is pushed, an application context66will be created alongside if this is necessary.  As a result, you can67ignore the existence of the application context unless you need it.6869The second way is the explicit way using the70:meth:`~flask.Flask.app_context` method::7172    from flask import Flask, current_app7374    app = Flask(__name__)75    with app.app_context():76        # within this block, current_app points to app.77        print current_app.name7879The application context is also used by the :func:`~flask.url_for`80function in case a ``SERVER_NAME`` was configured.  This allows you to81generate URLs even in the absence of a request.8283If no request context has been pushed and an application context has84not been explicitly set, a ``RuntimeError`` will be raised. ::8586    RuntimeError: Working outside of application context.8788Locality of the Context89-----------------------9091The application context is created and destroyed as necessary.  It never92moves between threads and it will not be shared between requests.  As such93it is the perfect place to store database connection information and other94things.  The internal stack object is called :data:`flask._app_ctx_stack`.95Extensions are free to store additional information on the topmost level,96assuming they pick a sufficiently unique name and should put their97information there, instead of on the :data:`flask.g` object which is reserved98for user code.99100For more information about that, see :ref:`extension-dev`.101102Context Usage103-------------104105The context is typically used to cache resources that need to be created106on a per-request or usage case.  For instance, database connections are107destined to go there.  When storing things on the application context108unique names should be chosen as this is a place that is shared between109Flask applications and extensions.110111The most common usage is to split resource management into two parts:1121131.  an implicit resource caching on the context.1142.  a context teardown based resource deallocation.115116Generally there would be a ``get_X()`` function that creates resource117``X`` if it does not exist yet and otherwise returns the same resource,118and a ``teardown_X()`` function that is registered as teardown handler.119120This is an example that connects to a database::121122    import sqlite3123    from flask import g124125    def get_db():126        db = getattr(g, '_database', None)127        if db is None:128            db = g._database = connect_to_database()129        return db130131    @app.teardown_appcontext132    def teardown_db(exception):133        db = getattr(g, '_database', None)134        if db is not None:135            db.close()136137The first time ``get_db()`` is called the connection will be established.138To make this implicit a :class:`~werkzeug.local.LocalProxy` can be used::139140    from werkzeug.local import LocalProxy141    db = LocalProxy(get_db)142143That way a user can directly access ``db`` which internally calls144``get_db()``.