dbcon.rst
This file
Path
docs/tutorial/dbcon.rst
37 lines · 1.4 KiB
Last changed by
Added lazyloading pattern and explicit chapter links in tutorial.Armin Ronacherbefore adoption9d19b77
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` and12:meth:`~flask.Flask.after_request` decorators::1314 @app.before_request15 def before_request():16 g.db = connect_db()1718 @app.after_request19 def after_request(response):20 g.db.close()21 return response2223Functions marked with :meth:`~flask.Flask.before_request` are called before24a request and passed no arguments, functions marked with25:meth:`~flask.Flask.after_request` are called after a request and26passed the response that will be sent to the client. They have to return27that response object or a different one. In this case we just return it28unchanged.2930We store our current database connection on the special :data:`~flask.g`31object that flask provides for us. This object stores information for one32request only and is available from within each function. Never store such33things on other objects because this would not work with threaded34environments. That special :data:`~flask.g` object does some magic behind35the scenes to ensure it does the right thing.3637Continue to :ref:`tutorial-views`.