Updated documentation to use teardown request where appropriate
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 ba6bf23 · Browse files · 4 files·+45 added−40 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+45 added−40 removed
- other:+45 added−40 removed
Provenance
- Commit
a9fc040- Tree
0b69f4c- Author
Armin Ronacher <armin.ronacher@active-4.com>- Committer
Armin Ronacher <armin.ronacher@active-4.com>- Parent
ba6bf23
4 files changed+45 added−40 removed
modified:docs/patterns/sqlalchemy.rst+4 added-6 removed
63 unmodified lines64 automatically remove database sessions at the end of the request for you::65 66 from yourapplication.database import db_session67 68- @app.after_request69- def shutdown_session(response):68+ @app.teardown_request69+ def shutdown_session(exception=None):70 db_session.remove()71- return response71 72 Here is an example model (put this into `models.py`, e.g.)::73 74 from sqlalchemy import Column, Integer, String63 unmodified lines138 each request. Put this into your application module::139 140 from yourapplication.database import db_session141 143- @app.after_request144- def shutdown_session(response):142+ @app.teardown_request143+ def shutdown_session(exception=None):144 db_session.remove()146- return response145 146 Here is an example table and model (put this into `models.py`)::147 148 from sqlalchemy import Table, Column, Integer, String66 unmodified linesmodified:docs/patterns/sqlite3.rst+28 added-4 removed
3 unmodified lines4 =========================5 6 In Flask you can implement the opening of database connections at the7 beginning of the request and closing at the end with the8-:meth:`~flask.Flask.before_request` and :meth:`~flask.Flask.after_request`8+:meth:`~flask.Flask.before_request` and :meth:`~flask.Flask.teardown_request`9 decorators in combination with the special :class:`~flask.g` object.10 11 So here is a simple example of how you can use SQLite 3 with Flask::12 8 unmodified lines21 @app.before_request22 def before_request():23 g.db = connect_db()24 25- @app.after_request26- def after_request(response):25+ @app.teardown_request26+ def teardown_request(exception):27 g.db.close()28- return response28 29+Connect on Demand30+-----------------31+32+The downside of this approach is that this will only work if Flask33+executed the before-request handlers for you. If you are attempting to34+use the database from a script or the interactive Python shell you would35+have to do something like this::36+37+ with app.test_request_context()38+ app.preprocess_request()39+ # now you can use the g.db object40+41+In order to trigger the execution of the connection code. You won't be42+able to drop the dependency on the request context this way, but you could43+make it so that the application connects when necessary::44+45+ def get_connection():46+ db = getattr(g, '_db', None)47+ if db is None:48+ db = g._db = connect_db()49+ return db50+51+Downside here is that you have to use ``db = get_connection()`` instead of52+just being able to use ``g.db`` directly.53+54 .. _easy-querying:55 56 Easy Querying57 -------------54 unmodified linesmodified:docs/tutorial/dbcon.rst+8 added-23 removed
7 unmodified lines8 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`,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::12+:meth:`~flask.Flask.teardown_request` and :meth:`~flask.Flask.teardown_request`13+decorators::14 15 @app.before_request16 def before_request():17 g.db = connect_db()18 21- @app.after_request22- 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-19 @app.teardown_request20 def teardown_request(exception):21 g.db.close()22 23 Functions marked with :meth:`~flask.Flask.before_request` are called before24 a request and passed no arguments. Functions marked with39-:meth:`~flask.Flask.after_request` are called after a request and25+:meth:`~flask.Flask.teardown_request` are called after a request and26 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 the27+that response object or a different one. They are however not guaranteed28+to be executed if an exception is raised, this is where functions marked with29+:meth:`~flask.Flask.teardown_request` come in. They get called after the30 response has been constructed. They are not allowed to modify the request, and31 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.32+being processed, it is passed to each function; otherwise, `None` is passed in.33 34 We store our current database connection on the special :data:`~flask.g`50-object that flask provides for us. This object stores information for one35+object that Flask provides for us. This object stores information for one36 request only and is available from within each function. Never store such37 things on other objects because this would not work with threaded38 environments. That special :data:`~flask.g` object does some magic behind39 the scenes to ensure it does the right thing.2 unmodified linesmodified:docs/extensiondev.rst+5 added-7 removed
180 unmodified lines181 182 def __init__(self, app):183 self.app = app184 self.app.config.setdefault('SQLITE3_DATABASE', ':memory:')185- self.app.after_request(self.after_request)185+ self.app.teardown_request(self.teardown_request)186 self.app.before_request(self.before_request)187 188 def connect(self):189 return sqlite3.connect(self.app.config['SQLITE3_DATABASE'])1 unmodified line191 def before_request(self):192 ctx = _request_ctx_stack.top193 ctx.sqlite3_db = self.connect()194 195- def after_request(self, response):195+ def teardown_request(self, exception):196 ctx = _request_ctx_stack.top197 ctx.sqlite3_db.close()198- return response198 199 def get_db(self):200 ctx = _request_ctx_stack.top201 if ctx is not None:7 unmodified lines209 SQLite.210 2. We create a class for our extension that requires a supplied `app` object,211 sets a configuration for the database if it's not there212 (:meth:`dict.setdefault`), and attaches `before_request` and214- `after_request` handlers.213+ `teardown_request` handlers.214 3. Next, we define a `connect` function that opens a database connection.215 4. Then we set up the request handlers we bound to the app above. Note here216 that we're attaching our database connection to the top request context via217 `_request_ctx_stack.top`. Extensions should use the top context and not the44 unmodified lines262 263 def init_app(self, app):264 self.app = app265 self.app.config.setdefault('SQLITE3_DATABASE', ':memory:')267- self.app.after_request(self.after_request)266+ self.app.teardown_request(self.teardown_request)267 self.app.before_request(self.before_request)268 269 def connect(self):270 return sqlite3.connect(app.config['SQLITE3_DATABASE'])1 unmodified line272 def before_request(self):273 ctx = _request_ctx_stack.top274 ctx.sqlite3_db = self.connect()275 277- def after_request(self, response):276+ def teardown_request(self, exception):277 ctx = _request_ctx_stack.top278 ctx.sqlite3_db.close()280- return response279 280 def get_db(self):281 ctx = _request_ctx_stack.top282 if ctx is not None:78 unmodified lines