sqlite3.rst
This file
Path
docs/patterns/sqlite3.rst
111 lines · 3.5 KiB
Last changed by
Added a missing colonArmin Ronacherbefore adoption5ca17c8
History of this fileTake it
1.. _sqlite3:23Using SQLite 3 with Flask4=========================56In Flask you can implement the opening of database connections at the7beginning of the request and closing at the end with the8:meth:`~flask.Flask.before_request` and :meth:`~flask.Flask.teardown_request`9decorators in combination with the special :class:`~flask.g` object.1011So here is a simple example of how you can use SQLite 3 with Flask::1213 import sqlite314 from flask import g1516 DATABASE = '/path/to/database.db'1718 def connect_db():19 return sqlite3.connect(DATABASE)2021 @app.before_request22 def before_request():23 g.db = connect_db()2425 @app.teardown_request26 def teardown_request(exception):27 g.db.close()2829Connect on Demand30-----------------3132The downside of this approach is that this will only work if Flask33executed the before-request handlers for you. If you are attempting to34use the database from a script or the interactive Python shell you would35have to do something like this::3637 with app.test_request_context():38 app.preprocess_request()39 # now you can use the g.db object4041In order to trigger the execution of the connection code. You won't be42able to drop the dependency on the request context this way, but you could43make it so that the application connects when necessary::4445 def get_connection():46 db = getattr(g, '_db', None)47 if db is None:48 db = g._db = connect_db()49 return db5051Downside here is that you have to use ``db = get_connection()`` instead of52just being able to use ``g.db`` directly.5354.. _easy-querying:5556Easy Querying57-------------5859Now in each request handling function you can access `g.db` to get the60current open database connection. To simplify working with SQLite, a61helper function can be useful::6263 def query_db(query, args=(), one=False):64 cur = g.db.execute(query, args)65 rv = [dict((cur.description[idx][0], value)66 for idx, value in enumerate(row)) for row in cur.fetchall()]67 return (rv[0] if rv else None) if one else rv6869This handy little function makes working with the database much more70pleasant than it is by just using the raw cursor and connection objects.7172Here is how you can use it::7374 for user in query_db('select * from users'):75 print user['username'], 'has the id', user['user_id']7677Or if you just want a single result::7879 user = query_db('select * from users where username = ?',80 [the_username], one=True)81 if user is None:82 print 'No such user'83 else:84 print the_username, 'has the id', user['user_id']8586To pass variable parts to the SQL statement, use a question mark in the87statement and pass in the arguments as a list. Never directly add them to88the SQL statement with string formatting because this makes it possible89to attack the application using `SQL Injections90<http://en.wikipedia.org/wiki/SQL_injection>`_.9192Initial Schemas93---------------9495Relational databases need schemas, so applications often ship a96`schema.sql` file that creates the database. It's a good idea to provide97a function that creates the database based on that schema. This function98can do that for you::99100 from contextlib import closing101 102 def init_db():103 with closing(connect_db()) as db:104 with app.open_resource('schema.sql') as f:105 db.cursor().executescript(f.read())106 db.commit()107108You can then create such a database from the python shell:109110>>> from yourapplication import init_db111>>> init_db()