Added documentation for appcontext and teardown handlers
Before adoption: this commit came in with the history the project adopted, so no landing records it.
authored by Armin Ronacher · committed by Armin Ronacher · parent 34bbd31 · Browse files · 10 files·+287 added−64 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
10 files+287 added−64 removed
- other:+287 added−64 removed
Provenance
- Commit
9bed20c- Tree
859923f- Author
Armin Ronacher <armin.ronacher@active-4.com>- Committer
Armin Ronacher <armin.ronacher@active-4.com>- Parent
34bbd31
10 files changed+287 added−64 removed
modified:docs/api.rst+12 added-2 removed
467 unmodified lines468 469 .. data:: request_tearing_down470 471 This signal is sent when the application is tearing down the request.472- This is always called, even if an error happened. No arguments are473- provided.472+ This is always called, even if an error happened. An `exc` keyword473+ argument is passed with the exception that caused the teardown.474 475+ .. versionchanged:: 0.9476+ The `exc` parameter was added.477+478+.. data:: appcontext_tearing_down479+480+ This signal is sent when the application is tearing down the481+ application context. This is always called, even if an error happened.482+ An `exc` keyword argument is passed with the exception that caused the483+ teardown.484+485 .. currentmodule:: None486 487 .. class:: flask.signals.Namespace488 164 unmodified linesadded:docs/appcontext.rst+88 added
1+.. _app_context:2+3+The Application Context4+=======================5+6+.. versionadded:: 0.97+8+One of the design ideas behind Flask is that there are two different9+“states” in which code is executed. The application setup state in which10+the application implicitly is on the module level. It starts when the11+:class:`Flask` object is instantiated, and it implicitly ends when the12+first request comes in. While the application is in this state a few13+assumptions are true:14+15+- 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+21+On the contrast, during request handling, a couple of other rules exist: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.26+27+There is a third state which is sitting in between a little bit.28+Sometimes you are dealing with an application in a way that is similar to29+how you interact with applications during request handling just that there30+is no request active. Consider for instance that you're sitting in an31+interactive Python shell and interacting with the application, or a32+command line application.33+34+The application context is what powers the :data:`~flask.current_app`35+context local.36+37+Purpose of the Application Context38+----------------------------------39+40+The main reason for the application's context existance is that in the41+past a bunch of functionality was attached to the request context in lack42+of a better solution. Since one of the pillar's of Flask's design is that43+you can have more than one application in the same Python process.44+45+So how does the code find the “right” application? In the past we46+recommended passing applications around explicitly, but that caused issues47+with libraries that were not designed with that in mind for libraries for48+which it was too inconvenient to make this work.49+50+A common workaround for that problem was to use the51+:data:`~flask.current_app` proxy later on, which was bound to the current52+request's application reference. Since however creating such a request53+context is an unnecessarily expensive operation in case there is no54+request around, the application context was introduced.55+56+Creating an Application Context57+-------------------------------58+59+To make an application context there are two ways. The first one is the60+implicit one: whenever a request context is pushed, an application context61+will be created alongside if this is necessary. As a result of that, you62+can ignore the existance of the application context unless you need it.63+64+The second way is the explicit way using the65+:meth:`~flask.Flask.app_context` method::66+67+ from flask import Flask, current_app68+69+ app = Flask(__name__)70+ with app.app_context():71+ # within this block, current_app points to app.72+ print current_app.name73+74+The application context is also used by the :func:`~flask.url_for`75+function in case a ``SERVER_NAME`` was configured. This allows you to76+generate URLs even in the absence of a request.77+78+Locality of the Context79+-----------------------80+81+The application context is created and destroyed as necessary. It never82+moves between threads and it will not be shared between requests. As such83+it is the perfect place to store database connection information and other84+things. The internal stack object is called :data:`flask._app_ctx_stack`.85+Extensions are free to store additional information on the topmost level,86+assuming they pick a sufficiently unique name.87+88+For more information about that, see :ref:`extension-dev`.modified:docs/contents.rst.inc+1 added
16 unmodified lines17 errorhandling18 config19 signals20 views21+ appcontext22 reqcontext23 blueprints24 extensions25 shell32 unmodified linesmodified:docs/extensiondev.rst+69 added-31 removed
1+.. _extension-dev:2+3 Flask Extension Development4 ===========================5 6 Flask, being a microframework, often requires some repetitive steps to get146 unmodified lines153 What to use depends on what you have in mind. For the SQLite 3 extension154 we will use the class-based approach because it will provide users with an155 object that handles opening and closing database connections.156 157+What's important about classes is that they encourage to be shared around158+on module level. In that case, the object itself must not under any159+circumstances store any application specific state and must be shareable160+between different application.161+162 The Extension Code163 ------------------164 165 Here's the contents of the `flask_sqlite3.py` for copy/paste::166 167 import sqlite3168 169+ # Find the stack on which we want to store the database connection.170+ # Starting with Flask 0.9, the _app_ctx_stack is the correct one,171+ # before that we need to use the _request_ctx_stack.172+ try:173+ from flask import _app_ctx_stack as stack174+ except ImportError:162- from flask import _request_ctx_stack175+ from flask import _request_ctx_stack as stack176 177 178 class SQLite3(object):179 4 unmodified lines184 else:185 self.app = None186 187 def init_app(self, app):175- self.app = app176- self.app.config.setdefault('SQLITE3_DATABASE', ':memory:')177- self.app.teardown_request(self.teardown_request)178- self.app.before_request(self.before_request)188+ app.config.setdefault('SQLITE3_DATABASE', ':memory:')189+ # Use the newstyle teardown_appcontext if it's available,190+ # otherwise fall back to the request context191+ if hasattr(app, 'teardown_appcontext'):192+ app.teardown_appcontext(self.teardown)193+ else:194+ app.teardown_request(self.teardown)195 196 def connect(self):197 return sqlite3.connect(self.app.config['SQLITE3_DATABASE'])198 183- def before_request(self):184- ctx = _request_ctx_stack.top185- ctx.sqlite3_db = self.connect()199+ def teardown(self, exception):200+ ctx = stack.top201+ if hasattr(ctx, 'sqlite3_db'):202+ ctx.sqlite3_db.close()203 187- def teardown_request(self, exception):188- ctx = _request_ctx_stack.top189- ctx.sqlite3_db.close()190-204 @property205 def connection(self):193- ctx = _request_ctx_stack.top206+ ctx = stack.top207 if ctx is not None:208+ if not hasattr(ctx, 'sqlite3_db'):209+ ctx.sqlite3_db = self.connect()210 return ctx.sqlite3_db211 212 213 So here's what these lines of code do:4 unmodified lines218 instantiated without requiring an app object. This method supports the219 factory pattern for creating applications. The ``init_app`` will set the220 configuration for the database, defaulting to an in memory database if221 no configuration is supplied. In addition, the ``init_app`` method attaches207- ``before_request`` and ``teardown_request`` handlers.222+ the ``teardown`` handler. It will try to use the newstyle app context223+ handler and if it does not exist, falls back to the request context224+ one.225 3. Next, we define a ``connect`` method that opens a database connection.209-4. Then we set up the request handlers we bound to the app above. Note here210- that we're attaching our database connection to the top request context via211- ``_request_ctx_stack.top``. Extensions should use the top context and not the212- ``g`` object to store things like database connections.213-5. Finally, we add a ``connection`` property that simplifies access to the context's214- database.226+4. Finally, we add a ``connection`` property that on first access opens227+ the database connection and stores it on the context.228 229+ Note here that we're attaching our database connection to the top230+ application context via ``_app_ctx_stack.top``. Extensions should use231+ the top context for storing their own information with a sufficiently232+ complex name. Note that we're falling back to the233+ ``_request_ctx_stack.top`` if the application is using an older234+ version of Flask that does not support it.235+236 So why did we decide on a class-based approach here? Because using our237 extension looks something like this::238 239 from flask import Flask20 unmodified lines260 261 Keep in mind that supporting this factory pattern for creating apps is required262 for approved flask extensions (described below).263 264+.. admonition:: Note on ``init_app``265 245-Using _request_ctx_stack246-------------------------266+ As you noticed, ``init_app`` does not assign ``app`` to ``self``. This267+ is intentional! Class based Flask extensions must only store the268+ application on the object when the application was passed to the269+ constructor. This tells the extension: I am not interested in using270+ multiple applications.271 248-In the example above, before every request, a ``sqlite3_db`` variable is assigned249-to ``_request_ctx_stack.top``. In a view function, this variable is accessible250-using the ``connection`` property of ``SQLite3``. During the teardown of a251-request, the ``sqlite3_db`` connection is closed. By using this pattern, the252-*same* connection to the sqlite3 database is accessible to anything that needs it253-for the duration of the request.272+ When the extension needs to find the current application and it does273+ not have a reference to it, it must either use the274+ :data:`~flask.current_app` context local or change the API in a way275+ that you can pass the application explicitly.276 255-End-Of-Request Behavior256------------------------277 278+Using _app_ctx_stack279+--------------------280+281+In the example above, before every request, a ``sqlite3_db`` variable is282+assigned to ``_app_ctx_stack.top``. In a view function, this variable is283+accessible using the ``connection`` property of ``SQLite3``. During the284+teardown of a request, the ``sqlite3_db`` connection is closed. By using285+this pattern, the *same* connection to the sqlite3 database is accessible286+to anything that needs it for the duration of the request.287+288+If the :data:`~flask._app_ctx_stack` does not exist because the user uses289+an old version of Flask, it is recommended to fall back to290+:data:`~flask._request_ctx_stack` which is bound to a request.291+292+Teardown Behavior293+-----------------294+295+*This is only relevant if you want to support Flask 0.6 and older*296+297 Due to the change in Flask 0.7 regarding functions that are run at the end298 of the request your extension will have to be extra careful there if it299 wants to continue to support older versions of Flask. The following300 pattern is a good way to support both::7 unmodified lines308 app.teardown_request(close_connection)309 else:310 app.after_request(close_connection)311 273-312 Strictly speaking the above code is wrong, because teardown functions are313 passed the exception and typically don't return anything. However because314 the return value is discarded this will just work assuming that the code315 in between does not touch the passed parameter.93 unmodified linesmodified:docs/reqcontext.rst+5 added-21 removed
4 unmodified lines5 6 This document describes the behavior in Flask 0.7 which is mostly in line7 with the old behavior but has some small, subtle differences.8 9-One of the design ideas behind Flask is that there are two different10-“states” in which code is executed. The application setup state in which11-the application implicitly is on the module level. It starts when the12-:class:`Flask` object is instantiated, and it implicitly ends when the13-first request comes in. While the application is in this state a few14-assumptions are true:9+It is recommended that you read the :api:`app-context` chapter first.10 16-- the programmer can modify the application object safely.17-- no request handling happened so far18-- you have to have a reference to the application object in order to19- modify it, there is no magic proxy that can give you a reference to20- the application object you're currently creating or modifying.21-22-On the contrast, during request handling, a couple of other rules exist:23-24-- while a request is active, the context local objects25- (:data:`flask.request` and others) point to the current request.26-- any code can get hold of these objects at any time.27-28-The magic that makes this works is internally referred in Flask as the29-“request context”.30-11 Diving into Context Locals12 --------------------------13 14 Say you have a utility function that returns the URL the user should be71 unmodified lines86 the very top, :meth:`~flask.ctx.RequestContext.pop` removes it from the87 stack again. On popping the application's88 :func:`~flask.Flask.teardown_request` functions are also executed.89 90+Another thing of note is that the request context will automatically also91+create an :ref:`application context <app-context>` when it's pushed and92+there is no application context for that application so far.93+94 .. _callbacks-and-errors:95 96 Callbacks and Errors97 --------------------126 unmodified linesmodified:docs/signals.rst+23 added
266 unmodified lines267 268 from flask import request_tearing_down269 request_tearing_down.connect(close_db_connection, app)270 271+ As of Flask 0.9, this will also be passed an `exc` keyword argument272+ that has a reference to the exception that caused the teardown if273+ there was one.274+275+.. data:: flask.appcontext_tearing_down276+ :noindex:277+278+ This signal is sent when the app context is tearing down. This is always279+ called, even if an exception is caused. Currently functions listening280+ to this signal are called after the regular teardown handlers, but this281+ is not something you can rely on.282+283+ Example subscriber::284+285+ def close_db_connection(sender, **extra):286+ session.close()287+288+ from flask import request_tearing_down289+ appcontext_tearing_down.connect(close_db_connection, app)290+291+ This will also be passed an `exc` keyword argument that has a reference292+ to the exception that caused the teardown if there was one.293+294 .. _blinker: http://pypi.python.org/pypi/blinkermodified:flask/testsuite/appctx.py+12 added
51 unmodified lines52 with app.app_context():53 self.assert_equal(flask.current_app._get_current_object(), app)54 self.assert_equal(flask._app_ctx_stack.top, None)55 56+ def test_app_tearing_down(self):57+ cleanup_stuff = []58+ app = flask.Flask(__name__)59+ @app.teardown_appcontext60+ def cleanup(exception):61+ cleanup_stuff.append(exception)62 63+ with app.app_context():64+ pass65+66+ self.assert_equal(cleanup_stuff, [None])67+68+69 def suite():70 suite = unittest.TestSuite()71 suite.addTest(unittest.makeSuite(AppContextTestCase))72 return suitemodified:flask/app.py+62 added-6 removed
33 unmodified lines34 from .module import blueprint_is_module35 from .templating import DispatchingJinjaLoader, Environment, \36 _default_template_ctx_processor37 from .signals import request_started, request_finished, got_request_exception, \38- request_tearing_down38+ request_tearing_down, appcontext_tearing_down39 40 # a lock used for logger initialization41 _logger_lock = Lock()42 320 unmodified lines363 #:364 #: .. versionadded:: 0.7365 self.teardown_request_funcs = {}366 367+ #: A list of functions that are called when the application context368+ #: is destroyed. Since the application context is also torn down369+ #: if the request ends this is the place to store code that disconnects370+ #: from databases.371+ #:372+ #: .. versionadded:: 0.9373+ self.teardown_appcontext_funcs = []374+375 #: A dictionary with lists of functions that can be used as URL376 #: value processor functions. Whenever a URL is built these functions377 #: are called to modify the dictionary of values in place. The key378 #: `None` here is used for application wide734 unmodified lines1113 Generally teardown functions must take every necesary step to avoid1114 that they will fail. If they do execute code that might fail they1115 will have to surround the execution of these code by try/except1116 statements and log ocurring errors.1117+1118+ When a teardown function was called because of a exception it will1119+ be passed an error object.1120 """1121 self.teardown_request_funcs.setdefault(None, []).append(f)1122 return f1123 1124 @setupmethod1125+ def teardown_appcontext(self, f):1126+ """Registers a function to be called when the application context1127+ ends. These functions are typically also called when the request1128+ context is popped.1129+1130+ Example::1131+1132+ ctx = app.app_context()1133+ ctx.push()1134+ ...1135+ ctx.pop()1136+1137+ When ``ctx.pop()`` is executed in the above example, the teardown1138+ functions are called just before the app context moves from the1139+ stack of active contexts. This becomes relevant if you are using1140+ such constructs in tests.1141+1142+ Since a request context typically also manages an application1143+ context it would also be called when you pop a request context.1144+1145+ When a teardown function was called because of an exception it will1146+ be passed an error object.1147+1148+ .. versionadded:: 0.91149+ """1150+ self.teardown_appcontext_funcs.append(f)1151+ return f1152+1153+ @setupmethod1154 def context_processor(self, f):1155 """Registers a template context processor function."""1156 self.template_context_processors[None].append(f)1157 return f366 unmodified lines1524 if not self.session_interface.is_null_session(ctx.session):1525 self.save_session(ctx.session, response)1526 return response1527 1488- def do_teardown_request(self):1528+ def do_teardown_request(self, exc=None):1529 """Called after the actual request dispatching and will1530 call every as :meth:`teardown_request` decorated function. This is1531 not actually called by the :class:`Flask` object itself but is always1532 triggered when the request context is popped. That way we have a1533 tighter control over certain resources under testing environments.1534+1535+ .. versionchanged:: 0.91536+ Added the `exc` argument. Previously this was always using the1537+ current exception information.1538 """1539+ if exc is None:1540+ exc = sys.exc_info()[1]1541 funcs = reversed(self.teardown_request_funcs.get(None, ()))1542 bp = _request_ctx_stack.top.request.blueprint1543 if bp is not None and bp in self.teardown_request_funcs:1544 funcs = chain(funcs, reversed(self.teardown_request_funcs[bp]))1499- exc = sys.exc_info()[1]1545 for func in funcs:1546 rv = func(exc)1502- if rv is not None:1503- return rv1504- request_tearing_down.send(self)1547+ request_tearing_down.send(self, exc=exc)1548 1549+ def do_teardown_appcontext(self, exc=None):1550+ """Called when an application context is popped. This works pretty1551+ much the same as :meth:`do_teardown_request` but for the application1552+ context.1553+1554+ .. versionadded:: 0.91555+ """1556+ if exc is None:1557+ exc = sys.exc_info()[1]1558+ for func in reversed(self.teardown_appcontext_funcs):1559+ func(exc)1560+ appcontext_tearing_down.send(self, exc=exc)1561+1562 def app_context(self):1563 """Binds the application only. For as long as the application is bound1564 to the current context the :data:`flask.current_app` points to that1565 application. An application context is automatically created when a95 unmodified linesmodified:flask/ctx.py+14 added-4 removed
7 unmodified lines8 :copyright: (c) 2011 by Armin Ronacher.9 :license: BSD, see LICENSE for more details.10 """11 12+import sys13+14 from werkzeug.exceptions import HTTPException15 16 from .globals import _request_ctx_stack, _app_ctx_stack17 from .module import blueprint_is_module69 unmodified lines87 def push(self):88 """Binds the app context to the current context."""89 _app_ctx_stack.push(self)90 89- def pop(self):91+ def pop(self, exc=None):92 """Pops the app context."""93+ if exc is None:94+ exc = sys.exc_info()[1]95+ self.app.do_teardown_appcontext(exc)96 rv = _app_ctx_stack.pop()97 assert rv is self, 'Popped wrong app context. (%r instead of %r)' \98 % (rv, self)99 101 unmodified lines201 self.session = self.app.open_session(self.request)202 if self.session is None:203 self.session = self.app.make_null_session()204 200- def pop(self):205+ def pop(self, exc=None):206 """Pops the request context and unbinds it by doing that. This will207 also trigger the execution of functions registered by the208 :meth:`~flask.Flask.teardown_request` decorator.209+210+ .. versionchanged:: 0.9211+ Added the `exc` argument.212 """213 self.preserved = False214+ if exc is None:215+ exc = sys.exc_info()[1]206- self.app.do_teardown_request()216+ self.app.do_teardown_request(exc)217 rv = _request_ctx_stack.pop()218 assert rv is self, 'Popped wrong request context. (%r instead of %r)' \219 % (rv, self)220 19 unmodified lines240 if self.request.environ.get('flask._preserve_context') or \241 (tb is not None and self.app.preserve_context_on_exception):242 self.preserved = True243 else:234- self.pop()244+ self.pop(exc_value)245 246 def __repr__(self):247 return '<%s \'%s\' [%s] of %s>' % (248 self.__class__.__name__,4 unmodified linesmodified:flask/signals.py+1 added
47 unmodified lines48 request_started = _signals.signal('request-started')49 request_finished = _signals.signal('request-finished')50 request_tearing_down = _signals.signal('request-tearing-down')51 got_request_exception = _signals.signal('got-request-exception')52+appcontext_tearing_down = _signals.signal('appcontext-tearing-down')