appcontext.rst
This file
Path
docs/appcontext.rst
138 lines · 5.3 KiB
Last changed by
clean up code formatting in some docsDavid Lordbefore adoption1928f28
History of this fileTake it
The walk stopped after 200 commits: lines older than 86e8267 point at it.
Merge pull request #1378 from cbron/masterKeyan Pishdadianbefore adoption86e8267
lines 1–28why, one step back1.. _app-context:23The 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.2021In contrast, during request handling, a couple of other rules exist:2223- 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 tominor revision of documentation.bagrattebefore adoption9a80fe6
lines 29–30why, one step back29how you interact with applications during request handling; just that there30is no request active. Consider, for instance, that you're sitting in anMerge pull request #1378 from cbron/masterKeyan Pishdadianbefore adoption86e8267
lines 31–76why, one step back31interactive 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----------------------------------3940The main reason for the application's context existence is that in the41past a bunch of functionality was attached to the request context for lack42of a better solution. Since one of the pillars 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 issues47with libraries that were not designed with that in mind.4849A 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 creating such a request context is52an unnecessarily expensive operation in case there is no request around,53the application context was introduced.5455Creating an Application Context56-------------------------------5758There are two ways to make an application context. The first one is59implicit: whenever a request context is pushed, an application context60will be created alongside if this is necessary. As a result, you can61ignore the existence of the application context unless you need it.6263The 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.76clean up code formatting in some docsDavid Lordbefore adoption1928f28
lines 77–79why, one step back77If no request context has been pushed and an application context has78not been explicitly set, a ``RuntimeError`` will be raised. ::79Merge pull request #1861 from ryanbackman/masterJeff Widmanbefore adoption808d2cf
lines 80–81why, one step back80 RuntimeError: Working outside of application context.81Merge pull request #1378 from cbron/masterKeyan Pishdadianbefore adoption86e8267
lines 82–138why, one step back82Locality of the Context83-----------------------8485The application context is created and destroyed as necessary. It never86moves between threads and it will not be shared between requests. As such87it is the perfect place to store database connection information and other88things. The internal stack object is called :data:`flask._app_ctx_stack`.89Extensions are free to store additional information on the topmost level,90assuming they pick a sufficiently unique name and should put their91information there, instead of on the :data:`flask.g` object which is reserved92for user code.9394For more information about that, see :ref:`extension-dev`.9596Context Usage97-------------9899The context is typically used to cache resources that need to be created100on a per-request or usage case. For instance, database connections are101destined to go there. When storing things on the application context102unique names should be chosen as this is a place that is shared between103Flask applications and extensions.104105The most common usage is to split resource management into two parts:1061071. an implicit resource caching on the context.1082. a context teardown based resource deallocation.109110Generally there would be a ``get_X()`` function that creates resource111``X`` if it does not exist yet and otherwise returns the same resource,112and a ``teardown_X()`` function that is registered as teardown handler.113114This is an example that connects to a database::115116 import sqlite3117 from flask import g118119 def get_db():120 db = getattr(g, '_database', None)121 if db is None:122 db = g._database = connect_to_database()123 return db124125 @app.teardown_appcontext126 def teardown_db(exception):127 db = getattr(g, '_database', None)128 if db is not None:129 db.close()130131The first time ``get_db()`` is called the connection will be established.132To make this implicit a :class:`~werkzeug.local.LocalProxy` can be used::133134 from werkzeug.local import LocalProxy135 db = LocalProxy(get_db)136137That way a user can directly access ``db`` which internally calls138``get_db()``.