sqlite3.rst
This file
Path
docs/patterns/sqlite3.rst
87 lines · 2.6 KiB
Last changed by
Breaking docs up into smaller piecesArmin Ronacherbefore adoption123a1ad
History of this fileTake it
1.. _sqlite3:23Using SQLite 3 with Flask4=========================56In Flask you can implement opening of dabase connections at the beginning7of the request and closing at the end with the8:meth:`~flask.Flask.before_request` and :meth:`~flask.Flask.after_request`9decorators in combination with the special :class:`~flask.g` object.1011So here a simple example 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.after_request26 def after_request(response):27 g.db.close()28 return response2930.. _easy-querying:3132Easy Querying33-------------3435Now in each request handling function you can access `g.db` to get the36current open database connection. To simplify working with SQLite a37helper function can be useful::3839 def query_db(query, args=(), one=False):40 cur = g.db.execute(query, args)41 rv = [dict((cur.description[idx][0], value)42 for idx, value in enumerate(row)) for row in cur.fetchall()]43 return (rv[0] if rv else None) if one else rv4445This handy little function makes working with the database much more46pleasant than it is by just using the raw cursor and connection objects.4748Here is how you can use it::4950 for user in query_db('select * from users'):51 print user['username'], 'has the id', user['user_id']5253Or if you just want a single result::5455 user = query_db('select * from users where username = ?',56 [the_username], one=True)57 if user is None:58 print 'No such user'59 else:60 print the_username, 'has the id', user['user_id']6162To pass variable parts to the SQL statement, use a question mark in the63statement and pass in the arguments as a list. Never directly add them to64the SQL statement with string formattings because this makes it possible65to attack the application using `SQL Injections66<http://en.wikipedia.org/wiki/SQL_injection>`_.6768Initial Schemas69---------------7071Relational databases need schemas, so applications often ship a72`schema.sql` file that creates the database. It's a good idea to provide73a function that creates the database bases on that schema. This function74can do that for you::7576 from contextlib import closing77 78 def init_db():79 with closing(connect_db()) as db:80 with app.open_resource('schema.sql') as f:81 db.cursor().executescript(f.read())82 db.commit()8384You can then create such a database from the python shell:8586>>> from yourapplication import init_db87>>> init_db()