Skip to content
Myr

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

4 files+45 added−40 removed

modified:docs/patterns/sqlalchemy.rst+4 added-6 removed
63 unmodified lines
64automatically remove database sessions at the end of the request for you::6566 from yourapplication.database import db_session6768 @app.after_request69 def shutdown_session(response):68 @app.teardown_request69 def shutdown_session(exception=None):70 db_session.remove()71 return response7172Here is an example model (put this into `models.py`, e.g.)::7374 from sqlalchemy import Column, Integer, String
63 unmodified lines
138each request. Put this into your application module::139140 from yourapplication.database import db_session141143 @app.after_request144 def shutdown_session(response):142 @app.teardown_request143 def shutdown_session(exception=None):144 db_session.remove()146 return response145146Here is an example table and model (put this into `models.py`)::147148 from sqlalchemy import Table, Column, Integer, String
66 unmodified lines
modified:docs/patterns/sqlite3.rst+28 added-4 removed
3 unmodified lines
4=========================56In Flask you can implement the opening of database connections at the7beginning 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`9decorators in combination with the special :class:`~flask.g` object.1011So here is a simple example of how you can use SQLite 3 with Flask::12
8 unmodified lines
21 @app.before_request22 def before_request():23 g.db = connect_db()2425 @app.after_request26 def after_request(response):25 @app.teardown_request26 def teardown_request(exception):27 g.db.close()28 return response2829Connect on Demand30-----------------3132The downside of this approach is that this will only work if Flask33executed the before-request handlers for you. If you are attempting to34use the database from a script or the interactive Python shell you would35have to do something like this::3637 with app.test_request_context()38 app.preprocess_request()39 # now you can use the g.db object4041In order to trigger the execution of the connection code. You won't be42able to drop the dependency on the request context this way, but you could43make it so that the application connects when necessary::4445 def get_connection():46 db = getattr(g, '_db', None)47 if db is None:48 db = g._db = connect_db()49 return db5051Downside here is that you have to use ``db = get_connection()`` instead of52just being able to use ``g.db`` directly.5354.. _easy-querying:5556Easy Querying57-------------
54 unmodified lines
modified:docs/tutorial/dbcon.rst+8 added-23 removed
7 unmodified lines
8connection in all our functions so it makes sense to initialize them9before each request and shut them down afterwards.1011Flask allows us to do that with the :meth:`~flask.Flask.before_request`,12:meth:`~flask.Flask.after_request` and :meth:`~flask.Flask.teardown_request`13decorators. In debug mode, if an error is raised,14:meth:`~flask.Flask.after_request` won't be run, and you'll have access to the15db connection in the interactive debugger::12:meth:`~flask.Flask.teardown_request` and :meth:`~flask.Flask.teardown_request`13decorators::1415 @app.before_request16 def before_request():17 g.db = connect_db()1821 @app.after_request22 def after_request(response):23 g.db.close()24 return response2526If you want to guarantee that the connection is always closed in debug mode, you27can close it in a function decorated with :meth:`~flask.Flask.teardown_request`::2829 @app.before_request30 def before_request():31 g.db = connect_db()3219 @app.teardown_request20 def teardown_request(exception):21 g.db.close()2223Functions marked with :meth:`~flask.Flask.before_request` are called before24a 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 and26passed the response that will be sent to the client. They have to return41that response object or a different one. In this case we just return it42unchanged.4344Functions marked with :meth:`~flask.Flask.teardown_request` get called after the27that response object or a different one. They are however not guaranteed28to be executed if an exception is raised, this is where functions marked with29:meth:`~flask.Flask.teardown_request` come in. They get called after the30response has been constructed. They are not allowed to modify the request, and31their return values are ignored. If an exception occurred while the request was47being processed, it is passed to each function; otherwise, None is passed in.32being processed, it is passed to each function; otherwise, `None` is passed in.3334We store our current database connection on the special :data:`~flask.g`50object that flask provides for us. This object stores information for one35object that Flask provides for us. This object stores information for one36request only and is available from within each function. Never store such37things on other objects because this would not work with threaded38environments. That special :data:`~flask.g` object does some magic behind39the scenes to ensure it does the right thing.
2 unmodified lines
modified:docs/extensiondev.rst+5 added-7 removed
180 unmodified lines
181182 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)187188 def connect(self):189 return sqlite3.connect(self.app.config['SQLITE3_DATABASE'])
1 unmodified line
191 def before_request(self):192 ctx = _request_ctx_stack.top193 ctx.sqlite3_db = self.connect()194195 def after_request(self, response):195 def teardown_request(self, exception):196 ctx = _request_ctx_stack.top197 ctx.sqlite3_db.close()198 return response198199 def get_db(self):200 ctx = _request_ctx_stack.top201 if ctx is not None:
7 unmodified lines
209 SQLite.2102. 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.2143. Next, we define a `connect` function that opens a database connection.2154. 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 the
44 unmodified lines
262263 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)268269 def connect(self):270 return sqlite3.connect(app.config['SQLITE3_DATABASE'])
1 unmodified line
272 def before_request(self):273 ctx = _request_ctx_stack.top274 ctx.sqlite3_db = self.connect()275277 def after_request(self, response):276 def teardown_request(self, exception):277 ctx = _request_ctx_stack.top278 ctx.sqlite3_db.close()280 return response279280 def get_db(self):281 ctx = _request_ctx_stack.top282 if ctx is not None:
78 unmodified lines