Skip to content
Myr

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

10 files+287 added−64 removed

modified:docs/api.rst+12 added-2 removed
467 unmodified lines
468469.. data:: request_tearing_down470471 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.474475 .. versionchanged:: 0.9476 The `exc` parameter was added.477478.. data:: appcontext_tearing_down479480 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.484485.. currentmodule:: None486487.. class:: flask.signals.Namespace488
164 unmodified lines
added:docs/appcontext.rst+88 added
1.. _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.2021On the 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 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----------------------------------3940The main reason for the application's context existance is that in the41past a bunch of functionality was attached to the request context in lack42of 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 issues47with libraries that were not designed with that in mind for libraries for48which it was too inconvenient to make this work.4950A common workaround for that problem was to use the51:data:`~flask.current_app` proxy later on, which was bound to the current52request's application reference. Since however creating such a request53context is an unnecessarily expensive operation in case there is no54request around, the application context was introduced.5556Creating an Application Context57-------------------------------5859To make an application context there are two ways. The first one is the60implicit one: whenever a request context is pushed, an application context61will be created alongside if this is necessary. As a result of that, you62can ignore the existance of the application context unless you need it.6364The second way is the explicit way using the65:meth:`~flask.Flask.app_context` method::6667 from flask import Flask, current_app6869 app = Flask(__name__)70 with app.app_context():71 # within this block, current_app points to app.72 print current_app.name7374The application context is also used by the :func:`~flask.url_for`75function in case a ``SERVER_NAME`` was configured. This allows you to76generate URLs even in the absence of a request.7778Locality of the Context79-----------------------8081The application context is created and destroyed as necessary. It never82moves between threads and it will not be shared between requests. As such83it is the perfect place to store database connection information and other84things. The internal stack object is called :data:`flask._app_ctx_stack`.85Extensions are free to store additional information on the topmost level,86assuming they pick a sufficiently unique name.8788For more information about that, see :ref:`extension-dev`.
modified:docs/contents.rst.inc+1 added
16 unmodified lines
17 errorhandling18 config19 signals20 views21 appcontext22 reqcontext23 blueprints24 extensions25 shell
32 unmodified lines
modified:docs/extensiondev.rst+69 added-31 removed
1.. _extension-dev:23Flask Extension Development4===========================56Flask, being a microframework, often requires some repetitive steps to get
146 unmodified lines
153What to use depends on what you have in mind. For the SQLite 3 extension154we will use the class-based approach because it will provide users with an155object that handles opening and closing database connections.156157What's important about classes is that they encourage to be shared around158on module level. In that case, the object itself must not under any159circumstances store any application specific state and must be shareable160between different application.161162The Extension Code163------------------164165Here's the contents of the `flask_sqlite3.py` for copy/paste::166167 import sqlite3168169 # 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 stack176177178 class SQLite3(object):179
4 unmodified lines
184 else:185 self.app = None186187 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)195196 def connect(self):197 return sqlite3.connect(self.app.config['SQLITE3_DATABASE'])198183 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()203187 def teardown_request(self, exception):188 ctx = _request_ctx_stack.top189 ctx.sqlite3_db.close()190204 @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_db211212213So here's what these lines of code do:
4 unmodified lines
218 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.2253. Next, we define a ``connect`` method that opens a database connection.2094. 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.2135. Finally, we add a ``connection`` property that simplifies access to the context's214 database.2264. Finally, we add a ``connection`` property that on first access opens227 the database connection and stores it on the context.228229 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.235236So why did we decide on a class-based approach here? Because using our237extension looks something like this::238239 from flask import Flask
20 unmodified lines
260261Keep in mind that supporting this factory pattern for creating apps is required262for approved flask extensions (described below).263264.. admonition:: Note on ``init_app``265245Using _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.271248In the example above, before every request, a ``sqlite3_db`` variable is assigned249to ``_request_ctx_stack.top``. In a view function, this variable is accessible250using the ``connection`` property of ``SQLite3``. During the teardown of a251request, the ``sqlite3_db`` connection is closed. By using this pattern, the252*same* connection to the sqlite3 database is accessible to anything that needs it253for 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.276255End-Of-Request Behavior256-----------------------277278Using _app_ctx_stack279--------------------280281In the example above, before every request, a ``sqlite3_db`` variable is282assigned to ``_app_ctx_stack.top``. In a view function, this variable is283accessible using the ``connection`` property of ``SQLite3``. During the284teardown of a request, the ``sqlite3_db`` connection is closed. By using285this pattern, the *same* connection to the sqlite3 database is accessible286to anything that needs it for the duration of the request.287288If the :data:`~flask._app_ctx_stack` does not exist because the user uses289an old version of Flask, it is recommended to fall back to290:data:`~flask._request_ctx_stack` which is bound to a request.291292Teardown Behavior293-----------------294295*This is only relevant if you want to support Flask 0.6 and older*296297Due to the change in Flask 0.7 regarding functions that are run at the end298of the request your extension will have to be extra careful there if it299wants to continue to support older versions of Flask. The following300pattern is a good way to support both::
7 unmodified lines
308 app.teardown_request(close_connection)309 else:310 app.after_request(close_connection)311273312Strictly speaking the above code is wrong, because teardown functions are313passed the exception and typically don't return anything. However because314the return value is discarded this will just work assuming that the code315in between does not touch the passed parameter.
93 unmodified lines
modified:docs/reqcontext.rst+5 added-21 removed
4 unmodified lines
56This document describes the behavior in Flask 0.7 which is mostly in line7with the old behavior but has some small, subtle differences.89One of the design ideas behind Flask is that there are two different10“states” in which code is executed. The application setup state in which11the application implicitly is on the module level. It starts when the12:class:`Flask` object is instantiated, and it implicitly ends when the13first request comes in. While the application is in this state a few14assumptions are true:9It is recommended that you read the :api:`app-context` chapter first.1016- 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.2122On the contrast, during request handling, a couple of other rules exist:2324- 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.2728The magic that makes this works is internally referred in Flask as the29“request context”.3011Diving into Context Locals12--------------------------1314Say you have a utility function that returns the URL the user should be
71 unmodified lines
86the very top, :meth:`~flask.ctx.RequestContext.pop` removes it from the87stack again. On popping the application's88:func:`~flask.Flask.teardown_request` functions are also executed.8990Another thing of note is that the request context will automatically also91create an :ref:`application context <app-context>` when it's pushed and92there is no application context for that application so far.9394.. _callbacks-and-errors:9596Callbacks and Errors97--------------------
126 unmodified lines
modified:docs/signals.rst+23 added
266 unmodified lines
267268 from flask import request_tearing_down269 request_tearing_down.connect(close_db_connection, app)270271 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.274275.. data:: flask.appcontext_tearing_down276 :noindex:277278 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.282283 Example subscriber::284285 def close_db_connection(sender, **extra):286 session.close()287288 from flask import request_tearing_down289 appcontext_tearing_down.connect(close_db_connection, app)290291 This will also be passed an `exc` keyword argument that has a reference292 to the exception that caused the teardown if there was one.293294.. _blinker: http://pypi.python.org/pypi/blinker
modified:flask/testsuite/appctx.py+12 added
51 unmodified lines
52 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)5556 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)6263 with app.app_context():64 pass6566 self.assert_equal(cleanup_stuff, [None])676869def suite():70 suite = unittest.TestSuite()71 suite.addTest(unittest.makeSuite(AppContextTestCase))72 return suite
modified:flask/app.py+62 added-6 removed
33 unmodified lines
34from .module import blueprint_is_module35from .templating import DispatchingJinjaLoader, Environment, \36 _default_template_ctx_processor37from .signals import request_started, request_finished, got_request_exception, \38 request_tearing_down38 request_tearing_down, appcontext_tearing_down3940# a lock used for logger initialization41_logger_lock = Lock()42
320 unmodified lines
363 #:364 #: .. versionadded:: 0.7365 self.teardown_request_funcs = {}366367 #: 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 = []374375 #: 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 wide
734 unmodified lines
1113 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.11171118 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 f11231124 @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.11291130 Example::11311132 ctx = app.app_context()1133 ctx.push()1134 ...1135 ctx.pop()11361137 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.11411142 Since a request context typically also manages an application1143 context it would also be called when you pop a request context.11441145 When a teardown function was called because of an exception it will1146 be passed an error object.11471148 .. versionadded:: 0.91149 """1150 self.teardown_appcontext_funcs.append(f)1151 return f11521153 @setupmethod1154 def context_processor(self, f):1155 """Registers a template context processor function."""1156 self.template_context_processors[None].append(f)1157 return f
366 unmodified lines
1524 if not self.session_interface.is_null_session(ctx.session):1525 self.save_session(ctx.session, response)1526 return response15271488 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.15341535 .. 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)15481549 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.15531554 .. 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)15611562 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 a
95 unmodified lines
modified:flask/ctx.py+14 added-4 removed
7 unmodified lines
8 :copyright: (c) 2011 by Armin Ronacher.9 :license: BSD, see LICENSE for more details.10"""1112import sys1314from werkzeug.exceptions import HTTPException1516from .globals import _request_ctx_stack, _app_ctx_stack17from .module import blueprint_is_module
69 unmodified lines
87 def push(self):88 """Binds the app context to the current context."""89 _app_ctx_stack.push(self)9089 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 lines
201 self.session = self.app.open_session(self.request)202 if self.session is None:203 self.session = self.app.make_null_session()204200 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.209210 .. 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 lines
240 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)245246 def __repr__(self):247 return '<%s \'%s\' [%s] of %s>' % (248 self.__class__.__name__,
4 unmodified lines
modified:flask/signals.py+1 added
47 unmodified lines
48request_started = _signals.signal('request-started')49request_finished = _signals.signal('request-finished')50request_tearing_down = _signals.signal('request-tearing-down')51got_request_exception = _signals.signal('got-request-exception')52appcontext_tearing_down = _signals.signal('appcontext-tearing-down')