Skip to content
Myr

dbcon.rst

This file

Path

docs/tutorial/dbcon.rst

33 lines · 1.4 KiB

Last changed by

New style for the documentation. Looks more like the website now.Armin Ronacherbefore adoptionbcf347f

History of this file

Take it

1Step 4: Request Database Connections2------------------------------------34Now we know how we can open database connections and use them for scripts,5but how can we elegantly do that for requests?  We will need the database6connection in all our functions so it makes sense to initialize them7before each request and shut them down afterwards.89Flask allows us to do that with the :meth:`~flask.Flask.before_request` and10:meth:`~flask.Flask.after_request` decorators::1112    @app.before_request13    def before_request():14        g.db = connect_db()1516    @app.after_request17    def after_request(response):18        g.db.close()19        return response2021Functions marked with :meth:`~flask.Flask.before_request` are called before22a request and passed no arguments, functions marked with23:meth:`~flask.Flask.after_request` are called after a request and24passed the response that will be sent to the client.  They have to return25that response object or a different one.  In this case we just return it26unchanged.2728We store our current database connection on the special :data:`~flask.g`29object that flask provides for us.  This object stores information for one30request only and is available from within each function.  Never store such31things on other objects because this would not work with threaded32environments.  That special :data:`~flask.g` object does some magic behind33the scenes to ensure it does the right thing.