sqlite3.rst
This file
Path
docs/patterns/sqlite3.rst
87 lines · 2.7 KiB
Last changed by
Minor sqlite3 documentation fixes (grammar, etc)Adam Zapletalbefore adoption4ed7a92
History of this fileTake it
The walk stopped after 200 commits: lines older than 9959ddd point at it.
Removed some unused codeArmin Ronacherbefore adoption9959ddd
lines 1–5why, one step back1.. _sqlite3:23Using SQLite 3 with Flask4=========================5Minor sqlite3 documentation fixes (grammar, etc)Adam Zapletalbefore adoption4ed7a92
lines 6–7why, one step back6In Flask you can implement the opening of database connections at the7beginning of the request and closing at the end with theRemoved some unused codeArmin Ronacherbefore adoption9959ddd
lines 8–10why, one step back8:meth:`~flask.Flask.before_request` and :meth:`~flask.Flask.after_request`9decorators in combination with the special :class:`~flask.g` object.10Minor sqlite3 documentation fixes (grammar, etc)Adam Zapletalbefore adoption4ed7a92
line 11why, one step back11So here is a simple example of how you can use SQLite 3 with Flask::Removed some unused codeArmin Ronacherbefore adoption9959ddd
lines 12–35why, one step back1213 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 theMinor sqlite3 documentation fixes (grammar, etc)Adam Zapletalbefore adoption4ed7a92
line 36why, one step back36current open database connection. To simplify working with SQLite, aRemoved some unused codeArmin Ronacherbefore adoption9959ddd
lines 37–87why, one step back37helper 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 based 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()