Skip to content
Myr

sqlite3.rst

This file

Path

docs/patterns/sqlite3.rst

147 lines · 4.9 KiB

Last changed by

merge app and request context (#5812)David Lordbefore adoptionadf3636

History of this file

Take it

1Using SQLite 3 with Flask2=========================34You can implement a few functions to work with a SQLite connection during a5request context. The connection is created the first time it's accessed,6reused on subsequent access, until it is closed when the request context ends.78Here is a simple example of how you can use SQLite 3 with Flask::910    import sqlite311    from flask import g1213    DATABASE = '/path/to/database.db'1415    def get_db():16        db = getattr(g, '_database', None)17        if db is None:18            db = g._database = sqlite3.connect(DATABASE)19        return db2021    @app.teardown_appcontext22    def close_connection(exception):23        db = getattr(g, '_database', None)24        if db is not None:25            db.close()2627Now, to use the database, the application must either have an active28application context (which is always true if there is a request in flight)29or create an application context itself.  At that point the ``get_db``30function can be used to get the current database connection.  Whenever the31context is destroyed the database connection will be terminated.3233Example::3435    @app.route('/')36    def index():37        cur = get_db().cursor()38        ...394041.. note::4243   Please keep in mind that the teardown request and appcontext functions44   are always executed, even if a before-request handler failed or was45   never executed.  Because of this we have to make sure here that the46   database is there before we close it.4748Connect on Demand49-----------------5051The upside of this approach (connecting on first use) is that this will52only open the connection if truly necessary.  If you want to use this53code outside a request context you can use it in a Python shell by opening54the application context by hand::5556    with app.app_context():57        # now you can use get_db()585960Easy Querying61-------------6263Now in each request handling function you can access `get_db()` to get the64current open database connection.  To simplify working with SQLite, a65row factory function is useful.  It is executed for every result returned66from the database to convert the result.  For instance, in order to get67dictionaries instead of tuples, this could be inserted into the ``get_db``68function we created above::6970    def make_dicts(cursor, row):71        return dict((cursor.description[idx][0], value)72                    for idx, value in enumerate(row))7374    db.row_factory = make_dicts7576This will make the sqlite3 module return dicts for this database connection, which are much nicer to deal with. Even more simply, we could place this in ``get_db`` instead::7778    db.row_factory = sqlite3.Row7980This would use Row objects rather than dicts to return the results of queries. These are ``namedtuple`` s, so we can access them either by index or by key. For example, assuming we have a ``sqlite3.Row`` called ``r`` for the rows ``id``, ``FirstName``, ``LastName``, and ``MiddleInitial``::8182    >>> # You can get values based on the row's name83    >>> r['FirstName']84    John85    >>> # Or, you can get them based on index86    >>> r[1]87    John88    # Row objects are also iterable:89    >>> for value in r:90    ...     print(value)91    192    John93    Doe94    M9596Additionally, it is a good idea to provide a query function that combines97getting the cursor, executing and fetching the results::9899    def query_db(query, args=(), one=False):100        cur = get_db().execute(query, args)101        rv = cur.fetchall()102        cur.close()103        return (rv[0] if rv else None) if one else rv104105This handy little function, in combination with a row factory, makes106working with the database much more pleasant than it is by just using the107raw cursor and connection objects.108109Here is how you can use it::110111    for user in query_db('select * from users'):112        print(user['username'], 'has the id', user['user_id'])113114Or if you just want a single result::115116    user = query_db('select * from users where username = ?',117                    [the_username], one=True)118    if user is None:119        print('No such user')120    else:121        print(the_username, 'has the id', user['user_id'])122123To pass variable parts to the SQL statement, use a question mark in the124statement and pass in the arguments as a list.  Never directly add them to125the SQL statement with string formatting because this makes it possible126to attack the application using `SQL Injections127<https://en.wikipedia.org/wiki/SQL_injection>`_.128129Initial Schemas130---------------131132Relational databases need schemas, so applications often ship a133`schema.sql` file that creates the database.  It's a good idea to provide134a function that creates the database based on that schema.  This function135can do that for you::136137    def init_db():138        with app.app_context():139            db = get_db()140            with app.open_resource('schema.sql', mode='r') as f:141                db.cursor().executescript(f.read())142            db.commit()143144You can then create such a database from the Python shell:145146>>> from yourapplication import init_db147>>> init_db()