Skip to content
Myr

appcontext.rst

This file

Path

docs/appcontext.rst

133 lines · 5.2 KiB

Last changed by

Modernized docs in a few placesArmin Ronacherbefore adoption29bda59

History of this file

Take it

Fixed some smaller things in the docsArmin Ronacherbefore adoptiond26af4f

line 1why, one step back
1.. _app-context:

Added documentation for appcontext and teardown handlersArmin Ronacherbefore adoption9bed20c

lines 2–20why, one step back
2
3The Application Context4=======================56.. versionadded:: 0.978One of the design ideas behind Flask is that there are two different9“states” in which code is executed. The application setup state in which10the application implicitly is on the module level. It starts when the11:class:`Flask` object is instantiated, and it implicitly ends when the12first request comes in. While the application is in this state a few13assumptions are true:1415- the programmer can modify the application object safely.16- no request handling happened so far17- you have to have a reference to the application object in order to18 modify it, there is no magic proxy that can give you a reference to19 the application object you're currently creating or modifying.20

Merge pull request #634 from maxcountryman/masterKenneth Reitzbefore adoption4515b83

line 21why, one step back
21In contrast, during request handling, a couple of other rules exist:

Added documentation for appcontext and teardown handlersArmin Ronacherbefore adoption9bed20c

lines 22–39why, one step back
22
23- while a request is active, the context local objects24 (:data:`flask.request` and others) point to the current request.25- any code can get hold of these objects at any time.2627There is a third state which is sitting in between a little bit.28Sometimes you are dealing with an application in a way that is similar to29how you interact with applications during request handling just that there30is no request active. Consider for instance that you're sitting in an31interactive Python shell and interacting with the application, or a32command line application.3334The application context is what powers the :data:`~flask.current_app`35context local.3637Purpose of the Application Context38----------------------------------39

Merge pull request #591 from finbarrocallaghan/masterArmin Ronacherbefore adoption39329bf

line 40why, one step back
40The main reason for the application's context existence is that in the

Added documentation for appcontext and teardown handlersArmin Ronacherbefore adoption9bed20c

lines 41–46why, one step back
41past a bunch of functionality was attached to the request context in lack
42of a better solution. Since one of the pillar's of Flask's design is that43you can have more than one application in the same Python process.4445So how does the code find the “right” application? In the past we46recommended passing applications around explicitly, but that caused issues

Merge branch 'master' of github.com:mitsuhiko/flaskArmin Ronacherbefore adoption7fc0ddb

line 47why, one step back
47with libraries that were not designed with that in mind.

Added documentation for appcontext and teardown handlersArmin Ronacherbefore adoption9bed20c

lines 48–60why, one step back
48
49A common workaround for that problem was to use the50:data:`~flask.current_app` proxy later on, which was bound to the current51request's application reference. Since however creating such a request52context is an unnecessarily expensive operation in case there is no53request around, the application context was introduced.5455Creating an Application Context56-------------------------------5758To make an application context there are two ways. The first one is the59implicit one: whenever a request context is pushed, an application context60will be created alongside if this is necessary. As a result of that, you

Merge pull request #591 from finbarrocallaghan/masterArmin Ronacherbefore adoption39329bf

line 61why, one step back
61can ignore the existence of the application context unless you need it.

Added documentation for appcontext and teardown handlersArmin Ronacherbefore adoption9bed20c

lines 62–84why, one step back
62
63The second way is the explicit way using the64:meth:`~flask.Flask.app_context` method::6566 from flask import Flask, current_app6768 app = Flask(__name__)69 with app.app_context():70 # within this block, current_app points to app.71 print current_app.name7273The application context is also used by the :func:`~flask.url_for`74function in case a ``SERVER_NAME`` was configured. This allows you to75generate URLs even in the absence of a request.7677Locality of the Context78-----------------------7980The application context is created and destroyed as necessary. It never81moves between threads and it will not be shared between requests. As such82it is the perfect place to store database connection information and other83things. The internal stack object is called :data:`flask._app_ctx_stack`.84Extensions are free to store additional information on the topmost level,

Modernized docs in a few placesArmin Ronacherbefore adoption29bda59

lines 85–87why, one step back
85assuming they pick a sufficiently unique name and should put there
86information there, instead on the :data:`flask.g` object which is reserved87for user code.

Added documentation for appcontext and teardown handlersArmin Ronacherbefore adoption9bed20c

lines 88–89why, one step back
88
89For more information about that, see :ref:`extension-dev`.

Updated examples to new sqlite patterns and added new section to appcontext docsArmin Ronacherbefore adoptionc2e5799

lines 90–111why, one step back
90
91Context Usage92-------------9394The context is typically used to cache resources on there that need to be95created on a per-request or usage case. For instance database connects96are destined to go there. When storing things on the application context97unique names should be chosen as this is a place that is shared between98Flask applications and extensions.99100The most common usage is to split resource management into two parts:1011021. an implicit resource caching on the context.1032. a context teardown based resource deallocation.104105Generally there would be a ``get_X()`` function that creates resource106``X`` if it does not exist yet and otherwise returns the same resource,107and a ``teardown_X()`` function that is registered as teardown handler.108109This is an example that connects to a database::110111 import sqlite3

Modernized docs in a few placesArmin Ronacherbefore adoption29bda59

line 112why, one step back
112 from flask import g

Updated examples to new sqlite patterns and added new section to appcontext docsArmin Ronacherbefore adoptionc2e5799

lines 113–114why, one step back
113
114 def get_db():

Modernized docs in a few placesArmin Ronacherbefore adoption29bda59

lines 115–118why, one step back
115 db = getattr(g, '_database', None)
116 if db is None:117 db = g._database = connect_to_database()118 return db

Updated examples to new sqlite patterns and added new section to appcontext docsArmin Ronacherbefore adoptionc2e5799

lines 119–121why, one step back
119
120 @app.teardown_appcontext121 def teardown_db(exception):

Modernized docs in a few placesArmin Ronacherbefore adoption29bda59

lines 122–124why, one step back
122 db = getattr(g, '_database', None)
123 if db is not None:124 db.close()

Updated examples to new sqlite patterns and added new section to appcontext docsArmin Ronacherbefore adoptionc2e5799

lines 125–133why, one step back
125
126The first time ``get_db()`` is called the connection will be established.127To make this implicit a :class:`~werkzeug.local.LocalProxy` can be used::128129 from werkzeug.local import LocalProxy130 db = LocalProxy(get_db)131132That way a user can directly access ``db`` which internally calls133``get_db()``.