Skip to content
Myr

sqlite3.rst

This file

Path

docs/patterns/sqlite3.rst

154 lines · 5.0 KiB

Last changed by

resolve merge conflictsKenneth Reitzbefore adoption31174fe

History of this file

Take it

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

Updated intersphinxArmin Ronacherbefore adoptiond1821b3

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

resolve merge conflictsKenneth Reitzbefore adoption31174fe

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

Merge pull request #1192 from nluchs/patch-3Markus Unterwaditzerbefore adoption60fcc05

line 8why, one step back
8request).

Updated intersphinxArmin Ronacherbefore adoptiond1821b3

lines 9–28why, one step back
9
10Here is a simple example of how you can use SQLite 3 with Flask::1112 import sqlite313 from flask import g1415 DATABASE = '/path/to/database.db'1617 def get_db():18 db = getattr(g, '_database', None)19 if db is None:20 db = g._database = sqlite3.connect(DATABASE)21 return db2223 @app.teardown_appcontext24 def close_connection(exception):25 db = getattr(g, '_database', None)26 if db is not None:27 db.close()28

Merge pull request #1235 from flowerhack/masterMarkus Unterwaditzerbefore adoption70a33ed

lines 29–33why, one step back
29Now, to use the database, the application must either have an active
30application context (which is always true if there is a request in flight)31or create an application context itself. At that point the ``get_db``32function can be used to get the current database connection. Whenever the33context is destroyed the database connection will be terminated.

Updated intersphinxArmin Ronacherbefore adoptiond1821b3

lines 34–57why, one step back
34
35Note: if you use Flask 0.9 or older you need to use36``flask._app_ctx_stack.top`` instead of ``g`` as the :data:`flask.g`37object was bound to the request and not application context.3839Example::4041 @app.route('/')42 def index():43 cur = get_db().cursor()44 ...454647.. note::4849 Please keep in mind that the teardown request and appcontext functions50 are always executed, even if a before-request handler failed or was51 never executed. Because of this we have to make sure here that the52 database is there before we close it.5354Connect on Demand55-----------------5657The upside of this approach (connecting on first use) is that this will

Merge pull request #1192 from nluchs/patch-3Markus Unterwaditzerbefore adoption60fcc05

line 58why, one step back
58only open the connection if truly necessary. If you want to use this

Updated intersphinxArmin Ronacherbefore adoptiond1821b3

lines 59–72why, one step back
59code outside a request context you can use it in a Python shell by opening
60the application context by hand::6162 with app.app_context():63 # now you can use get_db()6465.. _easy-querying:6667Easy Querying68-------------6970Now in each request handling function you can access `g.db` to get the71current open database connection. To simplify working with SQLite, a72row factory function is useful. It is executed for every result returned

Merge pull request #1192 from nluchs/patch-3Markus Unterwaditzerbefore adoption60fcc05

line 73why, one step back
73from the database to convert the result. For instance, in order to get

resolve merge conflictsKenneth Reitzbefore adoption31174fe

lines 74–75why, one step back
74dictionaries instead of tuples, this could be inserted into the ``get_db``
75function we created above::

Updated intersphinxArmin Ronacherbefore adoptiond1821b3

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

resolve merge conflictsKenneth Reitzbefore adoption31174fe

line 83why, one step back
83This will make the sqlite3 module return dicts for this database connection, which are much nicer to deal with. Even more simply, we could place this in ``get_db`` instead::

Updated intersphinxArmin Ronacherbefore adoptiond1821b3

lines 84–86why, one step back
84
85 db.row_factory = sqlite3.Row86

resolve merge conflictsKenneth Reitzbefore adoption31174fe

lines 87–102why, one step back
87This would use Row objects rather than dicts to return the results of queries. These are ``namedtuple`` s, so we can access them either by index or by key. For example, assuming we have a ``sqlite3.Row`` called ``r`` for the rows ``id``, ``FirstName``, ``LastName``, and ``MiddleInitial``::
8889 >>> # You can get values based on the row's name90 >>> r['FirstName']91 John92 >>> # Or, you can get them based on index93 >>> r[1]94 John95 # Row objects are also iterable:96 >>> for value in r:97 ... print(value)98 199 John100 Doe101 M102

Merge pull request #1245 from Winnetou/patch-7Markus Unterwaditzerbefore adoptioneea9342

line 103why, one step back
103Additionally, it is a good idea to provide a query function that combines

Updated intersphinxArmin Ronacherbefore adoptiond1821b3

line 104why, one step back
104getting the cursor, executing and fetching the results::

resolve merge conflictsKenneth Reitzbefore adoption31174fe

line 105why, one step back
105

Updated intersphinxArmin Ronacherbefore adoptiond1821b3

lines 106–111why, one step back
106 def query_db(query, args=(), one=False):
107 cur = get_db().execute(query, args)108 rv = cur.fetchall()109 cur.close()110 return (rv[0] if rv else None) if one else rv111

resolve merge conflictsKenneth Reitzbefore adoption31174fe

lines 112–113why, one step back
112This handy little function, in combination with a row factory, makes
113working with the database much more pleasant than it is by just using the

Merge pull request #1192 from nluchs/patch-3Markus Unterwaditzerbefore adoption60fcc05

line 114why, one step back
114raw cursor and connection objects.

Updated intersphinxArmin Ronacherbefore adoptiond1821b3

lines 115–133why, one step back
115
116Here is how you can use it::117118 for user in query_db('select * from users'):119 print user['username'], 'has the id', user['user_id']120121Or if you just want a single result::122123 user = query_db('select * from users where username = ?',124 [the_username], one=True)125 if user is None:126 print 'No such user'127 else:128 print the_username, 'has the id', user['user_id']129130To pass variable parts to the SQL statement, use a question mark in the131statement and pass in the arguments as a list. Never directly add them to132the SQL statement with string formatting because this makes it possible133to attack the application using `SQL Injections

resolve merge conflictsKenneth Reitzbefore adoption31174fe

line 134why, one step back
134<https://en.wikipedia.org/wiki/SQL_injection>`_.

Updated intersphinxArmin Ronacherbefore adoptiond1821b3

lines 135–150why, one step back
135
136Initial Schemas137---------------138139Relational databases need schemas, so applications often ship a140`schema.sql` file that creates the database. It's a good idea to provide141a function that creates the database based on that schema. This function142can do that for you::143144 def init_db():145 with app.app_context():146 db = get_db()147 with app.open_resource('schema.sql', mode='r') as f:148 db.cursor().executescript(f.read())149 db.commit()150

Merge pull request #1245 from Winnetou/patch-7Markus Unterwaditzerbefore adoptioneea9342

line 151why, one step back
151You can then create such a database from the Python shell:

Updated intersphinxArmin Ronacherbefore adoptiond1821b3

lines 152–154why, one step back
152
153>>> from yourapplication import init_db154>>> init_db()