Skip to content
Myr

sqlite3.rst

This file

Path

docs/patterns/sqlite3.rst

138 lines · 4.3 KiB

Last changed by

Fixed sqlite3 pattern. This fixes #924Armin Ronacherbefore adoption6f44ca7

History of this file

Take it

1.. _sqlite3:23Using SQLite 3 with Flask4=========================56In Flask you can implement the opening of database connections on demand7and closing it when the context dies (usually at the end of the request)8easily.910Here is a simple example of how you can use SQLite 3 with Flask::1112    import sqlite313    from flask import g1415    DATABASE = '/path/to/database.db'1617    def get_db():18        db = getattr(g, '_database', None)19        if db is None:20            db = g._database = sqlite3.connect(DATABASE)21        return db2223    @app.teardown_appcontext24    def close_connection(exception):25        db = getattr(g, '_database', None)26        if db is not None:27            db.close()2829All the application needs to do in order to now use the database is having30an active application context (which is always true if there is an request31in flight) or to create an application context itself.  At that point the32``get_db`` function can be used to get the current database connection.33Whenever the context is destroyed the database connection will be34terminated.3536Note: if you use Flask 0.9 or older you need to use37``flask._app_ctx_stack.top`` instead of ``g`` as the :data:`flask.g`38object was bound to the request and not application context.3940Example::4142    @app.route('/')43    def index():44        cur = get_db().cursor()45        ...464748.. note::4950   Please keep in mind that the teardown request and appcontext functions51   are always executed, even if a before-request handler failed or was52   never executed.  Because of this we have to make sure here that the53   database is there before we close it.5455Connect on Demand56-----------------5758The upside of this approach (connecting on first use) is that this will59only opening the connection if truly necessary.  If you want to use this60code outside a request context you can use it in a Python shell by opening61the application context by hand::6263    with app.app_context():64        # now you can use get_db()6566.. _easy-querying:6768Easy Querying69-------------7071Now in each request handling function you can access `g.db` to get the72current open database connection.  To simplify working with SQLite, a73row factory function is useful.  It is executed for every result returned74from the database to convert the result.  For instance in order to get75dictionaries instead of tuples this could be inserted into ``get_db``::7677    def make_dicts(cursor, row):78        return dict((cursor.description[idx][0], value)79                    for idx, value in enumerate(row))8081    db.row_factory = make_dicts8283Or even simpler::8485    db.row_factory = sqlite3.Row8687Additionally it is a good idea to provide a query function that combines88getting the cursor, executing and fetching the results::89    90    def query_db(query, args=(), one=False):91        cur = get_db().execute(query, args)92        rv = cur.fetchall()93        cur.close()94        return (rv[0] if rv else None) if one else rv9596This handy little function in combination with a row factory makes working97with the database much more pleasant than it is by just using the raw98cursor and connection objects.99100Here is how you can use it::101102    for user in query_db('select * from users'):103        print user['username'], 'has the id', user['user_id']104105Or if you just want a single result::106107    user = query_db('select * from users where username = ?',108                    [the_username], one=True)109    if user is None:110        print 'No such user'111    else:112        print the_username, 'has the id', user['user_id']113114To pass variable parts to the SQL statement, use a question mark in the115statement and pass in the arguments as a list.  Never directly add them to116the SQL statement with string formatting because this makes it possible117to attack the application using `SQL Injections118<http://en.wikipedia.org/wiki/SQL_injection>`_.119120Initial Schemas121---------------122123Relational databases need schemas, so applications often ship a124`schema.sql` file that creates the database.  It's a good idea to provide125a function that creates the database based on that schema.  This function126can do that for you::127128    def init_db():129        with app.app_context():130            db = get_db()131            with app.open_resource('schema.sql', mode='r') as f:132                db.cursor().executescript(f.read())133            db.commit()134135You can then create such a database from the python shell:136137>>> from yourapplication import init_db138>>> init_db()