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 fileTake it
The walk stopped after 200 commits: lines older than 2f60124 point at it.
Removed ridiculous constructor from AppGroupArmin Ronacherbefore adoption2f60124
lines 1–7why, one step back1.. _app-context:23The Application Context4=======================56.. versionadded:: 0.97fix doc build errorDavid Lordbefore adoptiond2a46dc
line 8why, one step back8One of the design ideas behind Flask is that there are at least twoMerge pull request #1887 from zevaverbach/patch-1Kenneth Reitzbefore adoption63ddf2d
line 9why, one step back9different “states” in which code is executed:Removed ridiculous constructor from AppGroupArmin Ronacherbefore adoption2f60124
line 10why, one step back10fix doc build errorDavid Lordbefore adoptiond2a46dc
lines 11–12why, one step back111. The application setup state, in which the application implicitly is12on the module level.Removed ridiculous constructor from AppGroupArmin Ronacherbefore adoption2f60124
line 13why, one step back13fix doc build errorDavid Lordbefore adoptiond2a46dc
lines 14–15why, one step back14 This state starts when the :class:`Flask` object is instantiated, and15 it implicitly ends when the first request comes in. While theMerge pull request #1887 from zevaverbach/patch-1Kenneth Reitzbefore adoption63ddf2d
line 16why, one step back16 application is in this state, a few assumptions are true:Removed ridiculous constructor from AppGroupArmin Ronacherbefore adoption2f60124
line 17why, one step back17Merge pull request #1887 from zevaverbach/patch-1Kenneth Reitzbefore adoption63ddf2d
lines 18–23why, one step back18 - 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.23fix doc build errorDavid Lordbefore adoptiond2a46dc
line 24why, one step back242. In contrast, in the request handling state, a couple of other rulesMerge pull request #1887 from zevaverbach/patch-1Kenneth Reitzbefore adoption63ddf2d
lines 25–27why, one step back25exist:2627 - while a request is active, the context local objectsfix doc build errorDavid Lordbefore adoptiond2a46dc
line 28why, one step back28 (:data:`flask.request` and others) point to the current request.Merge pull request #1887 from zevaverbach/patch-1Kenneth Reitzbefore adoption63ddf2d
line 29why, one step back29 - any code can get hold of these objects at any time.Removed ridiculous constructor from AppGroupArmin Ronacherbefore adoption2f60124
line 30why, one step back30fix doc build errorDavid Lordbefore adoptiond2a46dc
line 31why, one step back313. There is also a third state somewhere in between 'module-level' andMerge pull request #1887 from zevaverbach/patch-1Kenneth Reitzbefore adoption63ddf2d
lines 32–34why, one step back32'request-handling':3334 Sometimes you are dealing with an application in a way that is similar tofix doc build errorDavid Lordbefore adoptiond2a46dc
lines 35–37why, one step back35 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 theMerge pull request #1887 from zevaverbach/patch-1Kenneth Reitzbefore adoption63ddf2d
line 38why, one step back38 application, or a command line application.Removed ridiculous constructor from AppGroupArmin Ronacherbefore adoption2f60124
lines 39–46why, one step back3940The 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 theMerge pull request #1186 from llimllib/masterMarkus Unterwaditzerbefore adoptiona25ee7e
lines 47–48why, one step back47past 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 thatRemoved ridiculous constructor from AppGroupArmin Ronacherbefore adoption2f60124
lines 49–56why, one step back49you 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 currentMerge pull request #1186 from llimllib/masterMarkus Unterwaditzerbefore adoptiona25ee7e
lines 57–59why, one step back57request'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.Removed ridiculous constructor from AppGroupArmin Ronacherbefore adoption2f60124
lines 60–63why, one step back6061Creating an Application Context62-------------------------------63Merge pull request #1186 from llimllib/masterMarkus Unterwaditzerbefore adoptiona25ee7e
lines 64–67why, one step back64There 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.Removed ridiculous constructor from AppGroupArmin Ronacherbefore adoption2f60124
lines 68–81why, one step back6869The 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 back8283If 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.Removed ridiculous constructor from AppGroupArmin Ronacherbefore adoption2f60124
lines 87–104why, one step back8788Locality 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-------------104Merge pull request #1186 from llimllib/masterMarkus Unterwaditzerbefore adoptiona25ee7e
lines 105–107why, one step back105The 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 contextRemoved ridiculous constructor from AppGroupArmin Ronacherbefore adoption2f60124
lines 108–144why, one step back108unique 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()``.