Add teardown_request decorator. Fixes issue #174
Before adoption: this commit came in with the history the project adopted, so no landing records it.
authored by Matt Chisholm · committed by Armin Ronacher · parent 3deae1b · Browse files · 4 files·+136 added−4 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
4 files+136 added−4 removed
- tests:+73 added−1 removed
- other:+63 added−3 removed
Provenance
- Commit
04e70bd- Tree
72b5bfd- Author
Matt Chisholm <matt@theory.org>- Committer
Armin Ronacher <armin.ronacher@active-4.com>- Parent
3deae1b
4 files changed+136 added−4 removed
modified:docs/tutorial/dbcon.rst+22 added-3 removed
6 unmodified lines7 but how can we elegantly do that for requests? We will need the database8 connection in all our functions so it makes sense to initialize them9 before each request and shut them down afterwards.10 11-Flask allows us to do that with the :meth:`~flask.Flask.before_request` and12-:meth:`~flask.Flask.after_request` decorators::11+Flask allows us to do that with the :meth:`~flask.Flask.before_request`,12+:meth:`~flask.Flask.after_request` and :meth:`~flask.Flask.teardown_request`13+decorators. In debug mode, if an error is raised,14+:meth:`~flask.Flask.after_request` won't be run, and you'll have access to the15+db connection in the interactive debugger::16 17 @app.before_request18 def before_request():19 g.db = connect_db()2 unmodified lines22 def after_request(response):23 g.db.close()24 return response25 26+If you want to guarantee that the connection is always closed in debug mode, you27+can close it in a function decorated with :meth:`~flask.Flask.teardown_request`:28+29+ @app.before_request30+ def before_request():31+ g.db = connect_db()32+33+ @app.teardown_request34+ def teardown_request(exception):35+ g.db.close()36+37 Functions marked with :meth:`~flask.Flask.before_request` are called before24-a request and passed no arguments, functions marked with38+a request and passed no arguments. Functions marked with39 :meth:`~flask.Flask.after_request` are called after a request and40 passed the response that will be sent to the client. They have to return41 that response object or a different one. In this case we just return it42 unchanged.43 44+Functions marked with :meth:`~flask.Flask.teardown_request` get called after the45+response has been constructed. They are not allowed to modify the request, and46+their return values are ignored. If an exception occurred while the request was47+being processed, it is passed to each function; otherwise, None is passed in.48+49 We store our current database connection on the special :data:`~flask.g`50 object that flask provides for us. This object stores information for one51 request only and is available from within each function. Never store such52 things on other objects because this would not work with threaded4 unmodified linesmodified:flask/app.py+39 added
9 unmodified lines10 """11 12 from __future__ import with_statement13 14+import sys15 from threading import Lock16 from datetime import timedelta, datetime17 from itertools import chain18 228 unmodified lines247 #: currently logged in user. To register a function here, use the248 #: :meth:`after_request` decorator.249 self.after_request_funcs = {}250 251+ #: A dictionary with lists of functions that are called after252+ #: each request, even if an exception has occurred. The key of the253+ #: dictionary is the name of the module this function is active for,254+ #: `None` for all requests. These functions are not allowed to modify255+ #: the request, and their return values are ignored. If an exception256+ #: occurred while processing the request, it gets passed to each257+ #: teardown_request function. To register a function here, use the258+ #: :meth:`teardown_request` decorator.259+ #:260+ #: .. versionadded:: 0.7261+ self.teardown_request_funcs = {}262+263 #: A dictionary with list of functions that are called without argument264 #: to populate the template context. The key of the dictionary is the265 #: name of the module this function is active for, `None` for all266 #: requests. Each returns a dictionary that the template context is449 unmodified lines716 """Register a function to be run after each request."""717 self.after_request_funcs.setdefault(None, []).append(f)718 return f719 720+ def teardown_request(self, f):721+ """Register a function to be run at the end of each request, regardless of whether there was an exception or not."""722+ self.teardown_request_funcs.setdefault(None, []).append(f)723+ return f724+725 def context_processor(self, f):726 """Registers a template context processor function."""727 self.template_context_processors[None].append(f)728 return f157 unmodified lines886 for handler in funcs:887 response = handler(response)888 return response889 890+ def do_teardown_request(self):891+ """Called after the actual request dispatching and will892+ call every as :meth:`teardown_request` decorated function.893+ """894+ funcs = reversed(self.teardown_request_funcs.get(None, ()))895+ mod = request.module896+ if mod and mod in self.teardown_request_funcs:897+ funcs = chain(funcs, reversed(self.teardown_request_funcs[mod]))898+ exc = sys.exc_info()[1]899+ for func in funcs:900+ rv = func(exc)901+ if rv is not None:902+ return rv903+904 def request_context(self, environ):905 """Creates a request context from the given environment and binds906 it to the current context. This must be used in combination with907 the `with` statement because the request is only bound to the70 unmodified lines978 error handler took over request processing. This ensures that979 even if an exception happens database have the chance to980 properly close the connection.981 982+ .. versionchanged:: 0.7983+ The :meth:`teardown_request` functions get called at the very end of984+ processing the request. If an exception was thrown, it gets passed to985+ each teardown_request function.986+987 :param environ: a WSGI environment988 :param start_response: a callable accepting a status code,989 a list of headers and an optional990 exception context to start the response10 unmodified lines1001 try:1002 response = self.process_response(response)1003 except Exception, e:1004 response = self.make_response(self.handle_exception(e))1005+ finally:1006+ self.do_teardown_request()1007 request_finished.send(self, response=response)1008 return response(environ, start_response)1009 1010 def __call__(self, environ, start_response):2 unmodified linesmodified:tests/flask_tests.py+73 added-1 removed
411 unmodified lines412 assert rv.status_code == 500413 assert 'Internal Server Error' in rv.data414 assert len(called) == 1415 416+ def test_teardown_request_handler(self):417+ called = []418+ app = flask.Flask(__name__)419+ @app.teardown_request420+ def teardown_request(exc):421+ called.append(True)422+ return "Ignored"423+ @app.route('/')424+ def root():425+ return "Response"426+ rv = app.test_client().get('/')427+ assert rv.status_code == 200428+ assert 'Response' in rv.data429+ assert len(called) == 1430+431+ def test_teardown_request_handler_debug_mode(self):432+ called = []433+ app = flask.Flask(__name__)434+ app.debug = True435+ @app.teardown_request436+ def teardown_request(exc):437+ called.append(True)438+ return "Ignored"439+ @app.route('/')440+ def root():441+ return "Response"442+ rv = app.test_client().get('/')443+ assert rv.status_code == 200444+ assert 'Response' in rv.data445+ assert len(called) == 1446+447+448+ def test_teardown_request_handler_error(self):449+ called = []450+ app = flask.Flask(__name__)451+ @app.teardown_request452+ def teardown_request1(exc):453+ assert type(exc) == ZeroDivisionError454+ called.append(True)455+ # This raises a new error and blows away sys.exc_info(), so we can456+ # test that all teardown_requests get passed the same original457+ # exception.458+ try:459+ raise TypeError460+ except:461+ pass462+ @app.teardown_request463+ def teardown_request2(exc):464+ assert type(exc) == ZeroDivisionError465+ called.append(True)466+ # This raises a new error and blows away sys.exc_info(), so we can467+ # test that all teardown_requests get passed the same original468+ # exception.469+ try:470+ raise TypeError471+ except:472+ pass473+ @app.route('/')474+ def fails():475+ 1/0476+ rv = app.test_client().get('/')477+ assert rv.status_code == 500478+ assert 'Internal Server Error' in rv.data479+ assert len(called) == 2480+481+482 def test_before_after_request_order(self):483 called = []484 app = flask.Flask(__name__)485 @app.before_request9 unmodified lines495 @app.after_request496 def after2(response):497 called.append(3)498 return response499+ @app.teardown_request500+ def finish1(exc):501+ called.append(6)502+ @app.teardown_request503+ def finish2(exc):504+ called.append(5)505 @app.route('/')506 def index():507 return '42'508 rv = app.test_client().get('/')509 assert rv.data == '42'438- assert called == [1, 2, 3, 4]510+ assert called == [1, 2, 3, 4, 5, 6]511 512 def test_error_handling(self):513 app = flask.Flask(__name__)514 @app.errorhandler(404)1059 unmodified linesmodified:CHANGES+2 added
35 unmodified lines36 - Use Last-Modified for static file sending instead of Date which37 was incorrectly introduced in 0.6.38 - Added `create_jinja_loader` to override the loader creation process.39 - Implemented a silent flag for `config.from_pyfile`.40+- Added `teardown_request` decorator, for functions that should run at the end41+ of a request regardless of whether an exception occurred.42 43 Version 0.6.144 -------------45 159 unmodified lines