Skip to content
Myr

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 file

Take it

The walk stopped after 200 commits: lines older than a5a41d4 point at it.

Fix typo.Zhao Xiaohongbefore adoptiona5a41d4

lines 1–5why, one step back
1.. _sqlite3:
23Using SQLite 3 with Flask4=========================5

Minor sqlite3 documentation fixes (grammar, etc)Adam Zapletalbefore adoption4ed7a92

lines 6–7why, one step back
6In Flask you can implement the opening of database connections at the
7beginning of the request and closing at the end with the

Fix typo.Zhao Xiaohongbefore adoptiona5a41d4

lines 8–10why, one step back
8:meth:`~flask.Flask.before_request` and :meth:`~flask.Flask.after_request`
9decorators in combination with the special :class:`~flask.g` object.10

Minor sqlite3 documentation fixes (grammar, etc)Adam Zapletalbefore adoption4ed7a92

line 11why, one step back
11So here is a simple example of how you can use SQLite 3 with Flask::

Fix typo.Zhao Xiaohongbefore adoptiona5a41d4

lines 12–35why, one step back
12
13 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 the

Minor sqlite3 documentation fixes (grammar, etc)Adam Zapletalbefore adoption4ed7a92

line 36why, one step back
36current open database connection. To simplify working with SQLite, a

Fix typo.Zhao Xiaohongbefore adoptiona5a41d4

lines 37–87why, one step back
37helper 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()