Skip to content
Myr

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 file

Take it

The walk stopped after 200 commits: lines older than 405c299 point at it.

Updated from_pyfile so its dynamic module creation uses the imp module instead of type.Jeff Weberbefore adoption405c299

lines 1–7why, one step back
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 the

Merge branch 'new-request-dispatching' into blueprintsArmin Ronacherbefore adoption673fa18

line 8why, one step back
8:meth:`~flask.Flask.before_request` and :meth:`~flask.Flask.teardown_request`

Updated from_pyfile so its dynamic module creation uses the imp module instead of type.Jeff Weberbefore adoption405c299

lines 9–24why, one step back
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()24

Merge branch 'new-request-dispatching' into blueprintsArmin Ronacherbefore adoption673fa18

lines 25–26why, one step back
25 @app.teardown_request
26 def teardown_request(exception):

Updated from_pyfile so its dynamic module creation uses the imp module instead of type.Jeff Weberbefore adoption405c299

line 27why, one step back
27 g.db.close()

Merge branch 'new-request-dispatching' into blueprintsArmin Ronacherbefore adoption673fa18

lines 28–36why, one step back
28
29Connect 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::36

Added a missing colonArmin Ronacherbefore adoption5ca17c8

line 37why, one step back
37 with app.test_request_context():

Merge branch 'new-request-dispatching' into blueprintsArmin Ronacherbefore adoption673fa18

lines 38–52why, one step back
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.

Updated from_pyfile so its dynamic module creation uses the imp module instead of type.Jeff Weberbefore adoption405c299

lines 53–87why, one step back
53
54.. _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 to

Merge branch 'master' of github.com:mitsuhiko/flaskArmin Ronacherbefore adoption5ecf01d

line 88why, one step back
88the SQL statement with string formatting because this makes it possible

Updated from_pyfile so its dynamic module creation uses the imp module instead of type.Jeff Weberbefore adoption405c299

lines 89–111why, one step back
89to attack the application using `SQL Injections
90<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()