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 05c6502 point at it.
Let json.* work even without app on the stack and added testsArmin Ronacherbefore adoption05c6502
lines 1–5why, one step back1.. _sqlite3:23Using SQLite 3 with Flask4=========================5Updated examples to new sqlite patterns and added new section to appcontext docsArmin Ronacherbefore adoptionc2e5799
lines 6–8why, one step back6In 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.Let json.* work even without app on the stack and added testsArmin Ronacherbefore adoption05c6502
line 9why, one step back9Updated examples to new sqlite patterns and added new section to appcontext docsArmin Ronacherbefore adoptionc2e5799
line 10why, one step back10Here 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 back1112 import sqlite3Modernized docs in a few placesArmin Ronacherbefore adoption29bda59
line 13why, one step back13 from flask import gLet json.* work even without app on the stack and added testsArmin Ronacherbefore adoption05c6502
lines 14–16why, one step back1415 DATABASE = '/path/to/database.db'16Updated examples to new sqlite patterns and added new section to appcontext docsArmin Ronacherbefore adoptionc2e5799
line 17why, one step back17 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 dbLet json.* work even without app on the stack and added testsArmin Ronacherbefore adoption05c6502
line 22why, one step back22Updated examples to new sqlite patterns and added new section to appcontext docsArmin Ronacherbefore adoptionc2e5799
lines 23–24why, one step back23 @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()Let json.* work even without app on the stack and added testsArmin Ronacherbefore adoption05c6502
line 28why, one step back28Updated examples to new sqlite patterns and added new section to appcontext docsArmin Ronacherbefore adoptionc2e5799
lines 29–34why, one step back29All 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.Let json.* work even without app on the stack and added testsArmin Ronacherbefore adoption05c6502
line 39why, one step back39Updated examples to new sqlite patterns and added new section to appcontext docsArmin Ronacherbefore adoptionc2e5799
lines 40–47why, one step back40Example::4142 @app.route('/')43 def index():44 cur = get_db().cursor()45 ...4647Let json.* work even without app on the stack and added testsArmin Ronacherbefore adoption05c6502
lines 48–49why, one step back48.. note::49Updated examples to new sqlite patterns and added new section to appcontext docsArmin Ronacherbefore adoptionc2e5799
lines 50–53why, one step back50 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.Let json.* work even without app on the stack and added testsArmin Ronacherbefore adoption05c6502
lines 54–57why, one step back5455Connect on Demand56-----------------57Updated examples to new sqlite patterns and added new section to appcontext docsArmin Ronacherbefore adoptionc2e5799
lines 58–61why, one step back58The 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::Let json.* work even without app on the stack and added testsArmin Ronacherbefore adoption05c6502
line 62why, one step back62Updated examples to new sqlite patterns and added new section to appcontext docsArmin Ronacherbefore adoptionc2e5799
lines 63–64why, one step back63 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 back6566.. _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, aUpdated examples to new sqlite patterns and added new section to appcontext docsArmin Ronacherbefore adoptionc2e5799
lines 73–74why, one step back73row 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``::Let json.* work even without app on the stack and added testsArmin Ronacherbefore adoption05c6502
line 76why, one step back76Updated examples to new sqlite patterns and added new section to appcontext docsArmin Ronacherbefore adoptionc2e5799
line 77why, one step back77 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)Updated examples to new sqlite patterns and added new section to appcontext docsArmin Ronacherbefore adoptionc2e5799
lines 79–82why, one step back79 for idx, value in enumerate(row))8081 db.row_factory = make_dicts82Merge pull request #625 from soulseekah/masterKenneth Reitzbefore adoption3fdcefb
lines 83–86why, one step back83Or even simpler::8485 db.row_factory = sqlite3.Row86Updated examples to new sqlite patterns and added new section to appcontext docsArmin Ronacherbefore adoptionc2e5799
lines 87–89why, one step back87Additionally it is a good idea to provide a query function that combines88getting 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 back90 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 back91 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 back94 return (rv[0] if rv else None) if one else rv95Updated examples to new sqlite patterns and added new section to appcontext docsArmin Ronacherbefore adoptionc2e5799
lines 96–98why, one step back96This 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.Let json.* work even without app on the stack and added testsArmin Ronacherbefore adoption05c6502
lines 99–128why, one step back99100Here 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 back129 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:Let json.* work even without app on the stack and added testsArmin Ronacherbefore adoption05c6502
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()