Skip to content
Myr

sqlite3.rst

This file

Path

docs/patterns/sqlite3.rst

138 lines · 4.3 KiB

Last changed by

Fixed sqlite3 pattern. This fixes #924Armin Ronacherbefore adoption6f44ca7

History of this file

Take it

The walk stopped after 200 commits: lines older than 05c6502 point at it.

Let json.* work even without app on the stack and added testsArmin Ronacherbefore adoption05c6502

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.

Let json.* work even without app on the stack and added testsArmin Ronacherbefore adoption05c6502

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::

Let json.* work even without app on the stack and added testsArmin Ronacherbefore adoption05c6502

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

Let json.* work even without app on the stack and added testsArmin Ronacherbefore adoption05c6502

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–19why, one step back
18 db = getattr(g, '_database', None)
19 if db is None:

Fixed sqlite3 pattern. This fixes #924Armin Ronacherbefore adoption6f44ca7

line 20why, one step back
20 db = g._database = sqlite3.connect(DATABASE)

Modernized docs in a few placesArmin Ronacherbefore adoption29bda59

line 21why, one step back
21 return db

Let json.* work even without app on the stack and added testsArmin Ronacherbefore adoption05c6502

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()

Let json.* work even without app on the stack and added testsArmin Ronacherbefore adoption05c6502

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.

Let json.* work even without app on the stack and added testsArmin Ronacherbefore adoption05c6502

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

Let json.* work even without app on the stack and added testsArmin Ronacherbefore adoption05c6502

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.

Let json.* work even without app on the stack and added testsArmin Ronacherbefore adoption05c6502

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::

Let json.* work even without app on the stack and added testsArmin Ronacherbefore adoption05c6502

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()

Let json.* work even without app on the stack and added testsArmin Ronacherbefore adoption05c6502

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–74why, 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 get

Merge pull request #817 from llimllib/masterArmin Ronacherbefore adoption0893140

line 75why, one step back
75dictionaries instead of tuples this could be inserted into ``get_db``::

Let json.* work even without app on the stack and added testsArmin Ronacherbefore adoption05c6502

line 76why, one step back
76

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

line 77why, one step back
77 def make_dicts(cursor, row):

Merge pull request #817 from llimllib/masterArmin Ronacherbefore adoption0893140

line 78why, one step back
78 return dict((cursor.description[idx][0], value)

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

lines 79–82why, one step back
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

Let json.* work even without app on the stack and added testsArmin Ronacherbefore adoption05c6502

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()

Let json.* work even without app on the stack and added testsArmin Ronacherbefore adoption05c6502

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.

Let json.* work even without app on the stack and added testsArmin Ronacherbefore adoption05c6502

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:

Let json.* work even without app on the stack and added testsArmin Ronacherbefore adoption05c6502

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()