Skip to content
Myr

sqlite3.rst

This file

Path

docs/patterns/sqlite3.rst

134 lines · 4.2 KiB

Last changed by

Merge branch 'sprint-branch'Armin Ronacherbefore adoption29e63e0

History of this file

Take it

The walk stopped after 200 commits: lines older than 46e7bc7 point at it.

In Flask.run, now when the host/port argument is None, it will use its default value.Joe Espositobefore adoption46e7bc7

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.

In Flask.run, now when the host/port argument is None, it will use its default value.Joe Espositobefore adoption46e7bc7

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

In Flask.run, now when the host/port argument is None, it will use its default value.Joe Espositobefore adoption46e7bc7

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

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

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

In Flask.run, now when the host/port argument is None, it will use its default value.Joe Espositobefore adoption46e7bc7

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

lines 17–21why, one step back
17 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_db

In Flask.run, now when the host/port argument is None, it will use its default value.Joe Espositobefore adoption46e7bc7

line 22why, one step back
22

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

lines 23–27why, one step back
23 @app.teardown_appcontext
24 def close_connection(exception):25 top = _app_ctx_stack.top26 if hasattr(top, 'sqlite_db'):27 top.sqlite_db.close()

In Flask.run, now when the host/port argument is None, it will use its default value.Joe Espositobefore adoption46e7bc7

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.

In Flask.run, now when the host/port argument is None, it will use its default value.Joe Espositobefore adoption46e7bc7

line 35why, one step back
35

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

lines 36–43why, one step back
36Example::
3738 @app.route('/')39 def index():40 cur = get_db().cursor()41 ...4243

In Flask.run, now when the host/port argument is None, it will use its default value.Joe Espositobefore adoption46e7bc7

lines 44–45why, one step back
44.. note::
45

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

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

In Flask.run, now when the host/port argument is None, it will use its default value.Joe Espositobefore adoption46e7bc7

lines 50–53why, one step back
50
51Connect on Demand52-----------------53

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

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

In Flask.run, now when the host/port argument is None, it will use its default value.Joe Espositobefore adoption46e7bc7

line 58why, one step back
58

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

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

In Flask.run, now when the host/port argument is None, it will use its default value.Joe Espositobefore adoption46e7bc7

lines 61–68why, one step back
61
62.. _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, a

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

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

In Flask.run, now when the host/port argument is None, it will use its default value.Joe Espositobefore adoption46e7bc7

line 72why, one step back
72

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

lines 73–78why, one step back
73 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_dicts78

Merge pull request #625 from soulseekah/masterKenneth Reitzbefore adoption3fdcefb

lines 79–82why, one step back
79Or even simpler::
8081 db.row_factory = sqlite3.Row82

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

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

In Flask.run, now when the host/port argument is None, it will use its default value.Joe Espositobefore adoption46e7bc7

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

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

lines 87–89why, one step back
87 cur = get_db().execute(query, args)
88 rv = cur.fetchall()89 cur.close()

In Flask.run, now when the host/port argument is None, it will use its default value.Joe Espositobefore adoption46e7bc7

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

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

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

In Flask.run, now when the host/port argument is None, it will use its default value.Joe Espositobefore adoption46e7bc7

lines 95–124why, one step back
95
96Here is how you can use it::9798 for user in query_db('select * from users'):99 print user['username'], 'has the id', user['user_id']100101Or if you just want a single result::102103 user = query_db('select * from users where username = ?',104 [the_username], one=True)105 if user is None:106 print 'No such user'107 else:108 print the_username, 'has the id', user['user_id']109110To pass variable parts to the SQL statement, use a question mark in the111statement and pass in the arguments as a list. Never directly add them to112the SQL statement with string formatting because this makes it possible113to attack the application using `SQL Injections114<http://en.wikipedia.org/wiki/SQL_injection>`_.115116Initial Schemas117---------------118119Relational databases need schemas, so applications often ship a120`schema.sql` file that creates the database. It's a good idea to provide121a function that creates the database based on that schema. This function122can do that for you::123124 def init_db():

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

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

Merge branch 'sprint-branch'Armin Ronacherbefore adoption29e63e0

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

In Flask.run, now when the host/port argument is None, it will use its default value.Joe Espositobefore adoption46e7bc7

lines 128–134why, one step back
128 db.cursor().executescript(f.read())
129 db.commit()130131You can then create such a database from the python shell:132133>>> from yourapplication import init_db134>>> init_db()