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 fileTake it
The walk stopped after 200 commits: lines older than 0973536 point at it.
Added flask.copy_current_request_context which simplies working with greenletsArmin Ronacherbefore adoption0973536
lines 1–12why, one step back1.. _sqlite3:23Using SQLite 3 with Flask4=========================56In Flask you can implement the opening of database connections on demand7and closing it when the context dies (usually at the end of the request)8easily.910Here is a simple example of how you can use SQLite 3 with Flask::1112 import sqlite3Modernized docs in a few placesArmin Ronacherbefore adoption29bda59
line 13why, one step back13 from flask import gAdded flask.copy_current_request_context which simplies working with greenletsArmin Ronacherbefore adoption0973536
lines 14–17why, one step back1415 DATABASE = '/path/to/database.db'1617 def get_db():Modernized docs in a few placesArmin Ronacherbefore adoption29bda59
lines 18–19why, one step back18 db = getattr(g, '_database', None)19 if db is None:Fixed sqlite3 pattern. This fixes #924Armin Ronacherbefore adoption6f44ca7
line 20why, one step back20 db = g._database = sqlite3.connect(DATABASE)Modernized docs in a few placesArmin Ronacherbefore adoption29bda59
line 21why, one step back21 return dbAdded flask.copy_current_request_context which simplies working with greenletsArmin Ronacherbefore adoption0973536
lines 22–24why, one step back2223 @app.teardown_appcontext24 def close_connection(exception):Modernized docs in a few placesArmin Ronacherbefore adoption29bda59
lines 25–27why, one step back25 db = getattr(g, '_database', None)26 if db is not None:27 db.close()Added flask.copy_current_request_context which simplies working with greenletsArmin Ronacherbefore adoption0973536
lines 28–34why, one step back2829All the application needs to do in order to now use the database is having30an 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 back3536Note: 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.Added flask.copy_current_request_context which simplies working with greenletsArmin Ronacherbefore adoption0973536
lines 39–74why, one step back3940Example::4142 @app.route('/')43 def index():44 cur = get_db().cursor()45 ...464748.. note::4950 Please keep in mind that the teardown request and appcontext functions51 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.5455Connect on Demand56-----------------5758The upside of this approach (connecting on first use) is that this will59only 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::6263 with app.app_context():64 # now you can use get_db()6566.. _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, a73row factory function is useful. It is executed for every result returned74from the database to convert the result. For instance in order to getMerge pull request #817 from llimllib/masterArmin Ronacherbefore adoption0893140
line 75why, one step back75dictionaries instead of tuples this could be inserted into ``get_db``::Added flask.copy_current_request_context which simplies working with greenletsArmin Ronacherbefore adoption0973536
lines 76–77why, one step back7677 def make_dicts(cursor, row):Merge pull request #817 from llimllib/masterArmin Ronacherbefore adoption0893140
line 78why, one step back78 return dict((cursor.description[idx][0], value)Added flask.copy_current_request_context which simplies working with greenletsArmin Ronacherbefore adoption0973536
lines 79–130why, one step back79 for idx, value in enumerate(row))8081 db.row_factory = make_dicts8283Or even simpler::8485 db.row_factory = sqlite3.Row8687Additionally it is a good idea to provide a query function that combines88getting the cursor, executing and fetching the results::89 90 def query_db(query, args=(), one=False):91 cur = get_db().execute(query, args)92 rv = cur.fetchall()93 cur.close()94 return (rv[0] if rv else None) if one else rv9596This handy little function in combination with a row factory makes working97with the database much more pleasant than it is by just using the raw98cursor and connection objects.99100Here 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():129 with app.app_context():130 db = get_db()Merge branch 'sprint-branch'Armin Ronacherbefore adoption29e63e0
line 131why, one step back131 with app.open_resource('schema.sql', mode='r') as f:Added flask.copy_current_request_context which simplies working with greenletsArmin Ronacherbefore adoption0973536
lines 132–138why, one step back132 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()