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

The walk stopped after 200 commits: lines older than 7550f43 point at it.

Merge pull request #1185 from defuz/patch-2Markus Unterwaditzerbefore adoption7550f43

lines 1–7why, one step back
1.. _app-context:
23The Application Context4=======================56.. versionadded:: 0.97

fix doc build errorDavid Lordbefore adoptiond2a46dc

line 8why, one step back
8One of the design ideas behind Flask is that there are at least two

Merge pull request #1887 from zevaverbach/patch-1Kenneth Reitzbefore adoption63ddf2d

line 9why, one step back
9different “states” in which code is executed:

Merge pull request #1185 from defuz/patch-2Markus Unterwaditzerbefore adoption7550f43

line 10why, one step back
10

fix doc build errorDavid Lordbefore adoptiond2a46dc

lines 11–12why, one step back
111. The application setup state, in which the application implicitly is
12on the module level.

Merge pull request #1185 from defuz/patch-2Markus Unterwaditzerbefore adoption7550f43

line 13why, one step back
13

fix doc build errorDavid Lordbefore adoptiond2a46dc

lines 14–15why, one step back
14 This state starts when the :class:`Flask` object is instantiated, and
15 it implicitly ends when the first request comes in. While the

Merge pull request #1887 from zevaverbach/patch-1Kenneth Reitzbefore adoption63ddf2d

line 16why, one step back
16 application is in this state, a few assumptions are true:

Merge pull request #1185 from defuz/patch-2Markus Unterwaditzerbefore adoption7550f43

line 17why, one step back
17

Merge pull request #1887 from zevaverbach/patch-1Kenneth Reitzbefore adoption63ddf2d

lines 18–23why, one step back
18 - 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.23

fix doc build errorDavid Lordbefore adoptiond2a46dc

line 24why, one step back
242. In contrast, in the request handling state, a couple of other rules

Merge pull request #1887 from zevaverbach/patch-1Kenneth Reitzbefore adoption63ddf2d

lines 25–27why, one step back
25exist:
2627 - while a request is active, the context local objects

fix doc build errorDavid Lordbefore adoptiond2a46dc

line 28why, one step back
28 (:data:`flask.request` and others) point to the current request.

Merge pull request #1887 from zevaverbach/patch-1Kenneth Reitzbefore adoption63ddf2d

line 29why, one step back
29 - any code can get hold of these objects at any time.

Merge pull request #1185 from defuz/patch-2Markus Unterwaditzerbefore adoption7550f43

line 30why, one step back
30

fix doc build errorDavid Lordbefore adoptiond2a46dc

line 31why, one step back
313. There is also a third state somewhere in between 'module-level' and

Merge pull request #1887 from zevaverbach/patch-1Kenneth Reitzbefore adoption63ddf2d

lines 32–34why, one step back
32'request-handling':
3334 Sometimes you are dealing with an application in a way that is similar to

fix doc build errorDavid Lordbefore adoptiond2a46dc

lines 35–37why, one step back
35 how you interact with applications during request handling, but without
36 there being an active request. Consider, for instance, that you're37 sitting in an interactive Python shell and interacting with the

Merge pull request #1887 from zevaverbach/patch-1Kenneth Reitzbefore adoption63ddf2d

line 38why, one step back
38 application, or a command line application.

Merge pull request #1185 from defuz/patch-2Markus Unterwaditzerbefore adoption7550f43

lines 39–46why, one step back
39
40The 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 the

Merge pull request #1186 from llimllib/masterMarkus Unterwaditzerbefore adoptiona25ee7e

lines 47–48why, one step back
47past a bunch of functionality was attached to the request context for lack
48of a better solution. Since one of the pillars of Flask's design is that

Merge pull request #1185 from defuz/patch-2Markus Unterwaditzerbefore adoption7550f43

lines 49–56why, one step back
49you 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 current

Merge pull request #1186 from llimllib/masterMarkus Unterwaditzerbefore adoptiona25ee7e

lines 57–59why, one step back
57request's application reference. Since creating such a request context is
58an unnecessarily expensive operation in case there is no request around,59the application context was introduced.

Merge pull request #1185 from defuz/patch-2Markus Unterwaditzerbefore adoption7550f43

lines 60–63why, one step back
60
61Creating an Application Context62-------------------------------63

Merge pull request #1186 from llimllib/masterMarkus Unterwaditzerbefore adoptiona25ee7e

lines 64–67why, one step back
64There are two ways to make an application context. The first one is
65implicit: 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.

Merge pull request #1185 from defuz/patch-2Markus Unterwaditzerbefore adoption7550f43

lines 68–81why, one step back
68
69The 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.

resolve merge conflictsKenneth Reitzbefore adoption31174fe

lines 82–86why, one step back
82
83If 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.

Merge pull request #1185 from defuz/patch-2Markus Unterwaditzerbefore adoption7550f43

lines 87–104why, one step back
87
88Locality 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-------------104

Merge pull request #1186 from llimllib/masterMarkus Unterwaditzerbefore adoptiona25ee7e

lines 105–107why, one step back
105The context is typically used to cache resources that need to be created
106on a per-request or usage case. For instance, database connections are107destined to go there. When storing things on the application context

Merge pull request #1185 from defuz/patch-2Markus Unterwaditzerbefore adoption7550f43

lines 108–144why, one step back
108unique names should be chosen as this is a place that is shared between
109Flask 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()``.