sqlite3.rst
This file
Path
docs/patterns/sqlite3.rst
130 lines · 4.1 KiB
Last changed by
Updated examples to new sqlite patterns and added new section to appcontext docsArmin Ronacherbefore adoptionc2e5799
History of this fileTake 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 _app_ctx_stack1415 DATABASE = '/path/to/database.db'1617 def get_db():18 top = _app_ctx_stack.top19 if not hasattr(top, 'sqlite_db'):20 top.sqlite_db = sqlite3.connect(DATABASE)21 return top.sqlite_db2223 @app.teardown_appcontext24 def close_connection(exception):25 top = _app_ctx_stack.top26 if hasattr(top, 'sqlite_db'):27 top.sqlite_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.3536Example::3738 @app.route('/')39 def index():40 cur = get_db().cursor()41 ...424344.. note::4546 Please keep in mind that the teardown request and appcontext functions47 are always executed, even if a before-request handler failed or was48 never executed. Because of this we have to make sure here that the49 database is there before we close it.5051Connect on Demand52-----------------5354The upside of this approach (connecting on first use) is that this will55only opening the connection if truly necessary. If you want to use this56code outside a request context you can use it in a Python shell by opening57the application context by hand::5859 with app.app_context():60 # now you can use get_db()6162.. _easy-querying:6364Easy Querying65-------------6667Now in each request handling function you can access `g.db` to get the68current open database connection. To simplify working with SQLite, a69row factory function is useful. It is executed for every result returned70from the database to convert the result. For instance in order to get71dictionaries instead of tuples this can be used::7273 def make_dicts(cursor, row):74 return dict((cur.description[idx][0], value)75 for idx, value in enumerate(row))7677 db.row_factory = make_dicts7879Additionally it is a good idea to provide a query function that combines80getting the cursor, executing and fetching the results::81 82 def query_db(query, args=(), one=False):83 cur = get_db().execute(query, args)84 rv = cur.fetchall()85 cur.close()86 return (rv[0] if rv else None) if one else rv8788This handy little function in combination with a row factory makes working89with the database much more pleasant than it is by just using the raw90cursor and connection objects.9192Here is how you can use it::9394 for user in query_db('select * from users'):95 print user['username'], 'has the id', user['user_id']9697Or if you just want a single result::9899 user = query_db('select * from users where username = ?',100 [the_username], one=True)101 if user is None:102 print 'No such user'103 else:104 print the_username, 'has the id', user['user_id']105106To pass variable parts to the SQL statement, use a question mark in the107statement and pass in the arguments as a list. Never directly add them to108the SQL statement with string formatting because this makes it possible109to attack the application using `SQL Injections110<http://en.wikipedia.org/wiki/SQL_injection>`_.111112Initial Schemas113---------------114115Relational databases need schemas, so applications often ship a116`schema.sql` file that creates the database. It's a good idea to provide117a function that creates the database based on that schema. This function118can do that for you::119120 def init_db():121 with app.app_context():122 db = get_db()123 with app.open_resource('schema.sql') as f:124 db.cursor().executescript(f.read())125 db.commit()126127You can then create such a database from the python shell:128129>>> from yourapplication import init_db130>>> init_db()