Skip to content
Myr

sqlite3.rst

This file

Path

docs/patterns/sqlite3.rst

138 lines · 4.3 KiB

Last changed by

Modernized docs in a few placesArmin Ronacherbefore adoption29bda59

History of this file

Take it

The walk stopped after 200 commits: lines older than 3de8de1 point at it.

pip > easy_installKenneth Reitzbefore adoption3de8de1

lines 1–5why, one step back
1.. _sqlite3:
23Using SQLite 3 with Flask4=========================5

Updated examples to new sqlite patterns and added new section to appcontext docsArmin Ronacherbefore adoptionc2e5799

lines 6–8why, one step back
6In Flask you can implement the opening of database connections on demand
7and closing it when the context dies (usually at the end of the request)8easily.

pip > easy_installKenneth Reitzbefore adoption3de8de1

line 9why, one step back
9

Updated examples to new sqlite patterns and added new section to appcontext docsArmin Ronacherbefore adoptionc2e5799

line 10why, one step back
10Here is a simple example of how you can use SQLite 3 with Flask::

pip > easy_installKenneth Reitzbefore adoption3de8de1

lines 11–12why, one step back
11
12 import sqlite3

Modernized docs in a few placesArmin Ronacherbefore adoption29bda59

line 13why, one step back
13 from flask import g

pip > easy_installKenneth Reitzbefore adoption3de8de1

lines 14–16why, one step back
14
15 DATABASE = '/path/to/database.db'16

Updated examples to new sqlite patterns and added new section to appcontext docsArmin Ronacherbefore adoptionc2e5799

line 17why, one step back
17 def get_db():

Modernized docs in a few placesArmin Ronacherbefore adoption29bda59

lines 18–21why, one step back
18 db = getattr(g, '_database', None)
19 if db is None:20 db = g._database = connect_to_database()21 return db

pip > easy_installKenneth Reitzbefore adoption3de8de1

line 22why, one step back
22

Updated examples to new sqlite patterns and added new section to appcontext docsArmin Ronacherbefore adoptionc2e5799

lines 23–24why, one step back
23 @app.teardown_appcontext
24 def close_connection(exception):

Modernized docs in a few placesArmin Ronacherbefore adoption29bda59

lines 25–27why, one step back
25 db = getattr(g, '_database', None)
26 if db is not None:27 db.close()

pip > easy_installKenneth Reitzbefore adoption3de8de1

line 28why, one step back
28

Updated examples to new sqlite patterns and added new section to appcontext docsArmin Ronacherbefore adoptionc2e5799

lines 29–34why, one step back
29All the application needs to do in order to now use the database is having
30an 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.

Modernized docs in a few placesArmin Ronacherbefore adoption29bda59

lines 35–38why, one step back
35
36Note: 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.

pip > easy_installKenneth Reitzbefore adoption3de8de1

line 39why, one step back
39

Updated examples to new sqlite patterns and added new section to appcontext docsArmin Ronacherbefore adoptionc2e5799

lines 40–47why, one step back
40Example::
4142 @app.route('/')43 def index():44 cur = get_db().cursor()45 ...4647

pip > easy_installKenneth Reitzbefore adoption3de8de1

lines 48–49why, one step back
48.. note::
49

Updated examples to new sqlite patterns and added new section to appcontext docsArmin Ronacherbefore adoptionc2e5799

lines 50–53why, one step back
50 Please keep in mind that the teardown request and appcontext functions
51 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.

pip > easy_installKenneth Reitzbefore adoption3de8de1

lines 54–57why, one step back
54
55Connect on Demand56-----------------57

Updated examples to new sqlite patterns and added new section to appcontext docsArmin Ronacherbefore adoptionc2e5799

lines 58–61why, one step back
58The upside of this approach (connecting on first use) is that this will
59only 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::

pip > easy_installKenneth Reitzbefore adoption3de8de1

line 62why, one step back
62

Updated examples to new sqlite patterns and added new section to appcontext docsArmin Ronacherbefore adoptionc2e5799

lines 63–64why, one step back
63 with app.app_context():
64 # now you can use get_db()

pip > easy_installKenneth Reitzbefore adoption3de8de1

lines 65–72why, one step back
65
66.. _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, a

Updated examples to new sqlite patterns and added new section to appcontext docsArmin Ronacherbefore adoptionc2e5799

lines 73–75why, one step back
73row factory function is useful. It is executed for every result returned
74from the database to convert the result. For instance in order to get75dictionaries instead of tuples this can be used::

pip > easy_installKenneth Reitzbefore adoption3de8de1

line 76why, one step back
76

Updated examples to new sqlite patterns and added new section to appcontext docsArmin Ronacherbefore adoptionc2e5799

lines 77–82why, one step back
77 def make_dicts(cursor, row):
78 return dict((cur.description[idx][0], value)79 for idx, value in enumerate(row))8081 db.row_factory = make_dicts82

Merge pull request #625 from soulseekah/masterKenneth Reitzbefore adoption3fdcefb

lines 83–86why, one step back
83Or even simpler::
8485 db.row_factory = sqlite3.Row86

Updated examples to new sqlite patterns and added new section to appcontext docsArmin Ronacherbefore adoptionc2e5799

lines 87–89why, one step back
87Additionally it is a good idea to provide a query function that combines
88getting the cursor, executing and fetching the results::89

pip > easy_installKenneth Reitzbefore adoption3de8de1

line 90why, one step back
90 def query_db(query, args=(), one=False):

Updated examples to new sqlite patterns and added new section to appcontext docsArmin Ronacherbefore adoptionc2e5799

lines 91–93why, one step back
91 cur = get_db().execute(query, args)
92 rv = cur.fetchall()93 cur.close()

pip > easy_installKenneth Reitzbefore adoption3de8de1

lines 94–95why, one step back
94 return (rv[0] if rv else None) if one else rv
95

Updated examples to new sqlite patterns and added new section to appcontext docsArmin Ronacherbefore adoptionc2e5799

lines 96–98why, one step back
96This handy little function in combination with a row factory makes working
97with the database much more pleasant than it is by just using the raw98cursor and connection objects.

pip > easy_installKenneth Reitzbefore adoption3de8de1

lines 99–128why, one step back
99
100Here 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():

Updated examples to new sqlite patterns and added new section to appcontext docsArmin Ronacherbefore adoptionc2e5799

lines 129–130why, one step back
129 with app.app_context():
130 db = get_db()

Merge branch 'sprint-branch'Armin Ronacherbefore adoption29e63e0

line 131why, one step back
131 with app.open_resource('schema.sql', mode='r') as f:

pip > easy_installKenneth Reitzbefore adoption3de8de1

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