sqlite3.rst
This file
Path
docs/patterns/sqlite3.rst
119 lines · 3.8 KiB
Last changed by
Updated the docs and examples to non-failing teardown handlersArmin Ronacherbefore adoptiond3ca551
History of this fileTake it
The walk stopped after 200 commits: lines older than b64fa73 point at it.
HEAD is 0.8-devArmin Ronacherbefore adoptionb64fa73
lines 1–26why, one step back1.. _sqlite3:23Using SQLite 3 with Flask4=========================56In Flask you can implement the opening of database connections at the7beginning of the request and closing at the end with the8:meth:`~flask.Flask.before_request` and :meth:`~flask.Flask.teardown_request`9decorators in combination with the special :class:`~flask.g` object.1011So here is a simple example of how you can use SQLite 3 with Flask::1213 import sqlite314 from flask import g1516 DATABASE = '/path/to/database.db'1718 def connect_db():19 return sqlite3.connect(DATABASE)2021 @app.before_request22 def before_request():23 g.db = connect_db()2425 @app.teardown_request26 def teardown_request(exception):Updated the docs and examples to non-failing teardown handlersArmin Ronacherbefore adoptiond3ca551
lines 27–35why, one step back27 if hasattr(g, 'db'):28 g.db.close()2930.. note::3132 Please keep in mind that the teardown request functions are always33 executed, even if a before-request handler failed or was never34 executed. Because of this we have to make sure here that the database35 is there before we close it.HEAD is 0.8-devArmin Ronacherbefore adoptionb64fa73
lines 36–44why, one step back3637Connect on Demand38-----------------3940The downside of this approach is that this will only work if Flask41executed the before-request handlers for you. If you are attempting to42use the database from a script or the interactive Python shell you would43have to do something like this::44Added a missing colonArmin Ronacherbefore adoption5ca17c8
line 45why, one step back45 with app.test_request_context():HEAD is 0.8-devArmin Ronacherbefore adoptionb64fa73
lines 46–119why, one step back46 app.preprocess_request()47 # now you can use the g.db object4849In order to trigger the execution of the connection code. You won't be50able to drop the dependency on the request context this way, but you could51make it so that the application connects when necessary::5253 def get_connection():54 db = getattr(g, '_db', None)55 if db is None:56 db = g._db = connect_db()57 return db5859Downside here is that you have to use ``db = get_connection()`` instead of60just being able to use ``g.db`` directly.6162.. _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, a69helper function can be useful::7071 def query_db(query, args=(), one=False):72 cur = g.db.execute(query, args)73 rv = [dict((cur.description[idx][0], value)74 for idx, value in enumerate(row)) for row in cur.fetchall()]75 return (rv[0] if rv else None) if one else rv7677This handy little function makes working with the database much more78pleasant than it is by just using the raw cursor and connection objects.7980Here is how you can use it::8182 for user in query_db('select * from users'):83 print user['username'], 'has the id', user['user_id']8485Or if you just want a single result::8687 user = query_db('select * from users where username = ?',88 [the_username], one=True)89 if user is None:90 print 'No such user'91 else:92 print the_username, 'has the id', user['user_id']9394To pass variable parts to the SQL statement, use a question mark in the95statement and pass in the arguments as a list. Never directly add them to96the SQL statement with string formatting because this makes it possible97to attack the application using `SQL Injections98<http://en.wikipedia.org/wiki/SQL_injection>`_.99100Initial Schemas101---------------102103Relational databases need schemas, so applications often ship a104`schema.sql` file that creates the database. It's a good idea to provide105a function that creates the database based on that schema. This function106can do that for you::107108 from contextlib import closing109 110 def init_db():111 with closing(connect_db()) as db:112 with app.open_resource('schema.sql') as f:113 db.cursor().executescript(f.read())114 db.commit()115116You can then create such a database from the python shell:117118>>> from yourapplication import init_db119>>> init_db()