Skip to content
Myr

dbcon.rst

This file

Path

docs/tutorial/dbcon.rst

41 lines · 1.8 KiB

Last changed by

Merge branch 'new-request-dispatching' into blueprintsArmin Ronacherbefore adoption673fa18

History of this file

Take 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.teardown_request` and :meth:`~flask.Flask.teardown_request`13decorators::1415    @app.before_request16    def before_request():17        g.db = connect_db()1819    @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 with25:meth:`~flask.Flask.teardown_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.  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 was32being processed, it is passed to each function; otherwise, `None` is passed in.3334We store our current database connection on the special :data:`~flask.g`35object 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.4041Continue to :ref:`tutorial-views`.