dbcon.rst
This file
Path
docs/tutorial/dbcon.rst
56 lines · 2.3 KiB
Last changed by
Fixed a typo that was preventing second code block from appearing in a code blockKanak Kshetribefore adoption0e4cd2e
History of this fileTake it
1.. _tutorial-dbcon:23Step 4: Request Database Connections4------------------------------------56Now we know how we can open database connections and use them for scripts,7but how can we elegantly do that for requests? We will need the database8connection 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::1617 @app.before_request18 def before_request():19 g.db = connect_db()2021 @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()3233 @app.teardown_request34 def teardown_request(exception):35 g.db.close()3637Functions marked with :meth:`~flask.Flask.before_request` are called before38a request and passed no arguments. Functions marked with39:meth:`~flask.Flask.after_request` are called after a request and40passed 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 the45response has been constructed. They are not allowed to modify the request, and46their return values are ignored. If an exception occurred while the request was47being processed, it is passed to each function; otherwise, None is passed in.4849We store our current database connection on the special :data:`~flask.g`50object that flask provides for us. This object stores information for one51request only and is available from within each function. Never store such52things on other objects because this would not work with threaded53environments. That special :data:`~flask.g` object does some magic behind54the scenes to ensure it does the right thing.5556Continue to :ref:`tutorial-views`.