sqlite3.rst
This file
Path
docs/patterns/sqlite3.rst
137 lines · 4.3 KiB
Last changed by
Merge pull request #1245 from Winnetou/patch-7Markus Unterwaditzerbefore adoptioneea9342
History of this fileTake it
The walk stopped after 200 commits: lines older than bb0084f point at it.
Fix Py3 compat bugMarkus Unterwaditzerbefore adoptionbb0084f
lines 1–5why, one step back1.. _sqlite3:23Using SQLite 3 with Flask4=========================5Merge pull request #1192 from nluchs/patch-3Markus Unterwaditzerbefore adoption60fcc05
line 6why, one step back6In Flask you can easily implement the opening of database connections on Merge pull request #1245 from Winnetou/patch-7Markus Unterwaditzerbefore adoptioneea9342
line 7why, one step back7demand 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 back8request).Fix Py3 compat bugMarkus Unterwaditzerbefore adoptionbb0084f
lines 9–28why, one step back910Here 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()28Merge pull request #1235 from flowerhack/masterMarkus Unterwaditzerbefore adoption70a33ed
lines 29–33why, one step back29Now, to use the database, the application must either have an active30application 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.Fix Py3 compat bugMarkus Unterwaditzerbefore adoptionbb0084f
lines 34–57why, one step back3435Note: 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 willMerge pull request #1192 from nluchs/patch-3Markus Unterwaditzerbefore adoption60fcc05
line 58why, one step back58only open the connection if truly necessary. If you want to use thisFix Py3 compat bugMarkus Unterwaditzerbefore adoptionbb0084f
lines 59–72why, one step back59code outside a request context you can use it in a Python shell by opening60the 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 returnedMerge pull request #1192 from nluchs/patch-3Markus Unterwaditzerbefore adoption60fcc05
lines 73–74why, one step back73from the database to convert the result. For instance, in order to get74dictionaries instead of tuples, this could be inserted into ``get_db``::Fix Py3 compat bugMarkus Unterwaditzerbefore adoptionbb0084f
lines 75–85why, one step back7576 def make_dicts(cursor, row):77 return dict((cursor.description[idx][0], value)78 for idx, value in enumerate(row))7980 db.row_factory = make_dicts8182Or even simpler::8384 db.row_factory = sqlite3.Row85Merge pull request #1245 from Winnetou/patch-7Markus Unterwaditzerbefore adoptioneea9342
line 86why, one step back86Additionally, it is a good idea to provide a query function that combinesFix Py3 compat bugMarkus Unterwaditzerbefore adoptionbb0084f
lines 87–94why, one step back87getting the cursor, executing and fetching the results::88 89 def query_db(query, args=(), one=False):90 cur = get_db().execute(query, args)91 rv = cur.fetchall()92 cur.close()93 return (rv[0] if rv else None) if one else rv94Merge pull request #1192 from nluchs/patch-3Markus Unterwaditzerbefore adoption60fcc05
lines 95–97why, one step back95This handy little function, in combination with a row factory, makes 96working with the database much more pleasant than it is by just using the 97raw cursor and connection objects.Fix Py3 compat bugMarkus Unterwaditzerbefore adoptionbb0084f
lines 98–133why, one step back9899Here is how you can use it::100101 for user in query_db('select * from users'):102 print user['username'], 'has the id', user['user_id']103104Or if you just want a single result::105106 user = query_db('select * from users where username = ?',107 [the_username], one=True)108 if user is None:109 print 'No such user'110 else:111 print the_username, 'has the id', user['user_id']112113To pass variable parts to the SQL statement, use a question mark in the114statement and pass in the arguments as a list. Never directly add them to115the SQL statement with string formatting because this makes it possible116to attack the application using `SQL Injections117<http://en.wikipedia.org/wiki/SQL_injection>`_.118119Initial Schemas120---------------121122Relational databases need schemas, so applications often ship a123`schema.sql` file that creates the database. It's a good idea to provide124a function that creates the database based on that schema. This function125can do that for you::126127 def init_db():128 with app.app_context():129 db = get_db()130 with app.open_resource('schema.sql', mode='r') as f:131 db.cursor().executescript(f.read())132 db.commit()133Merge pull request #1245 from Winnetou/patch-7Markus Unterwaditzerbefore adoptioneea9342
line 134why, one step back134You can then create such a database from the Python shell:Fix Py3 compat bugMarkus Unterwaditzerbefore adoptionbb0084f
lines 135–137why, one step back135136>>> from yourapplication import init_db137>>> init_db()