Skip to content
Myr

Updated examples to new sqlite patterns and added new section to appcontext docs

Before adoption: this commit came in with the history the project adopted, so no landing records it.

authored by Armin Ronacher · committed by Armin Ronacher · parent 3e9f4e2 · Browse files · 4 files+169 added−104 removed
This commit

State

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Diff stats

4 files+169 added−104 removed

  • other:+169 added−104 removed

4 files+169 added−104 removed

modified:docs/patterns/sqlite3.rst+59 added-48 removed
1 unmodified line
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.6In 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.911So here is a simple example of how you can use SQLite 3 with Flask::10Here is a simple example of how you can use SQLite 3 with Flask::1112 import sqlite314 from flask import g13 from flask import _app_ctx_stack1415 DATABASE = '/path/to/database.db'1618 def connect_db():19 return sqlite3.connect(DATABASE)17 def get_db():18 top = _app_ctx_stack.top19 if not hasattr(top, 'sqlite_db'):20 top.sqlite_db = sqlite3.connect(DATABASE)21 return top.sqlite_db2221 @app.before_request22 def before_request():23 g.db = connect_db()23 @app.teardown_appcontext24 def close_connection(exception):25 top = _app_ctx_stack.top26 if hasattr(top, 'sqlite_db'):27 top.sqlite_db.close()2825 @app.teardown_request26 def teardown_request(exception):27 if hasattr(g, 'db'):28 g.db.close()29All 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.3536Example::3738 @app.route('/')39 def index():40 cur = get_db().cursor()41 ...424344.. note::4532 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.46 Please keep in mind that the teardown request and appcontext functions47 are always executed, even if a before-request handler failed or was48 never executed. Because of this we have to make sure here that the49 database is there before we close it.5051Connect on Demand52-----------------5340The 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::54The upside of this approach (connecting on first use) is that this will55only opening the connection if truly necessary. If you want to use this56code outside a request context you can use it in a Python shell by opening57the application context by hand::5845 with app.test_request_context():46 app.preprocess_request()47 # now you can use the g.db object59 with app.app_context():60 # now you can use get_db()6149In 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::69row factory function is useful. It is executed for every result returned70from the database to convert the result. For instance in order to get71dictionaries instead of tuples this can be used::7273 def make_dicts(cursor, row):74 return dict((cur.description[idx][0], value)75 for idx, value in enumerate(row))7677 db.row_factory = make_dicts7879Additionally it is a good idea to provide a query function that combines80getting the cursor, executing and fetching the results::81 82 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()]83 cur = get_db().execute(query, args)84 rv = cur.fetchall()85 cur.close()86 return (rv[0] if rv else None) if one else rv8777This handy little function makes working with the database much more78pleasant than it is by just using the raw cursor and connection objects.88This handy little function in combination with a row factory makes working89with the database much more pleasant than it is by just using the raw90cursor and connection objects.9192Here is how you can use it::9394 for user in query_db('select * from users'):
21 unmodified lines
116`schema.sql` file that creates the database. It's a good idea to provide117a function that creates the database based on that schema. This function118can do that for you::119108 from contextlib import closing109 120 def init_db():111 with closing(connect_db()) as db:121 with app.app_context():122 db = get_db()123 with app.open_resource('schema.sql') as f:124 db.cursor().executescript(f.read())125 db.commit()126
4 unmodified lines
modified:docs/appcontext.rst+44 added
83 unmodified lines
84Extensions are free to store additional information on the topmost level,85assuming they pick a sufficiently unique name.8687For more information about that, see :ref:`extension-dev`.8889Context Usage90-------------9192The context is typically used to cache resources on there that need to be93created on a per-request or usage case. For instance database connects94are destined to go there. When storing things on the application context95unique names should be chosen as this is a place that is shared between96Flask applications and extensions.9798The most common usage is to split resource management into two parts:991001. an implicit resource caching on the context.1012. a context teardown based resource deallocation.102103Generally there would be a ``get_X()`` function that creates resource104``X`` if it does not exist yet and otherwise returns the same resource,105and a ``teardown_X()`` function that is registered as teardown handler.106107This is an example that connects to a database::108109 import sqlite3110 from flask import _app_ctx_stack111112 def get_db():113 top = _app_ctx_stack.top114 if not hasattr(top, 'database'):115 top.database = connect_to_database()116 return top.database117118 @app.teardown_appcontext119 def teardown_db(exception):120 top = _app_ctx_stack.top121 if hasattr(top, 'database'):122 top.database.close()123124The first time ``get_db()`` is called the connection will be established.125To make this implicit a :class:`~werkzeug.local.LocalProxy` can be used::126127 from werkzeug.local import LocalProxy128 db = LocalProxy(get_db)129130That way a user can directly access ``db`` which internally calls131``get_db()``.
modified:examples/flaskr/flaskr.py+22 added-19 removed
9 unmodified lines
10 :license: BSD, see LICENSE for more details.11"""12from __future__ import with_statement13from sqlite3 import dbapi2 as sqlite314from contextlib import closing14from flask import Flask, request, session, g, redirect, url_for, abort, \16 render_template, flash15 render_template, flash, _app_ctx_stack1617# configuration18DATABASE = '/tmp/flaskr.db'19DEBUG = True
6 unmodified lines
26app.config.from_object(__name__)27app.config.from_envvar('FLASKR_SETTINGS', silent=True)282931def connect_db():32 """Returns a new connection to the database."""33 return sqlite3.connect(app.config['DATABASE'])343530def init_db():31 """Creates the database tables."""38 with closing(connect_db()) as db:32 with app.app_context():33 db = get_db()34 with app.open_resource('schema.sql') as f:35 db.cursor().executescript(f.read())36 db.commit()373844@app.before_request45def before_request():46 """Make sure we are connected to the database each request."""47 g.db = connect_db()39def get_db():40 """Opens a new database connection if there is none yet for the41 current application context.42 """43 top = _app_ctx_stack.top44 if not hasattr(top, 'sqlite_db'):45 top.sqlite_db = sqlite3.connect(app.config['DATABASE'])46 return top.sqlite_db474850@app.teardown_request51def teardown_request(exception):49@app.teardown_appcontext50def close_db_connection(exception):51 """Closes the database again at the end of the request."""52 top = _app_ctx_stack.top53 if hasattr(g, 'db'):54 g.db.close()53 if hasattr(top, 'sqlite_db'):54 top.sqlite_db.close()555657@app.route('/')58def show_entries():59 db = get_db()59 cur = g.db.execute('select title, text from entries order by id desc')60 cur = db.execute('select title, text from entries order by id desc')61 entries = [dict(title=row[0], text=row[1]) for row in cur.fetchall()]62 return render_template('show_entries.html', entries=entries)636465@app.route('/add', methods=['POST'])66def add_entry():67 if not session.get('logged_in'):68 abort(401)69 db = get_db()68 g.db.execute('insert into entries (title, text) values (?, ?)',70 db.execute('insert into entries (title, text) values (?, ?)',71 [request.form['title'], request.form['text']])70 g.db.commit()72 db.commit()73 flash('New entry was successfully posted')74 return redirect(url_for('show_entries'))7576
19 unmodified lines
96 return redirect(url_for('show_entries'))979899if __name__ == '__main__':100 init_db()101 app.run()
modified:examples/minitwit/minitwit.py+44 added-37 removed
11 unmodified lines
12import time13from sqlite3 import dbapi2 as sqlite314from hashlib import md515from datetime import datetime16from contextlib import closing16from flask import Flask, request, session, url_for, redirect, \18 render_template, abort, g, flash17 render_template, abort, g, flash, _app_ctx_stack18from werkzeug import check_password_hash, generate_password_hash192021# configuration
7 unmodified lines
29app.config.from_object(__name__)30app.config.from_envvar('MINITWIT_SETTINGS', silent=True)313234def connect_db():35 """Returns a new connection to the database."""36 return sqlite3.connect(app.config['DATABASE'])33def get_db():34 """Opens a new database connection if there is none yet for the35 current application context.36 """37 top = _app_ctx_stack.top38 if not hasattr(top, 'sqlite_db'):39 top.sqlite_db = sqlite3.connect(app.config['DATABASE'])40 top.sqlite_db.row_factory = sqlite3.Row41 return top.sqlite_db424344@app.teardown_appcontext45def close_database(exception):46 """Closes the database again at the end of the request."""47 top = _app_ctx_stack.top48 if hasattr(top, 'sqlite_db'):49 top.sqlite_db.close()505152def init_db():53 """Creates the database tables."""41 with closing(connect_db()) as db:54 with app.app_context():55 db = get_db()56 with app.open_resource('schema.sql') as f:57 db.cursor().executescript(f.read())58 db.commit()596061def query_db(query, args=(), one=False):62 """Queries the database and returns a list of dictionaries."""49 cur = g.db.execute(query, args)50 rv = [dict((cur.description[idx][0], value)51 for idx, value in enumerate(row)) for row in cur.fetchall()]63 cur = get_db().execute(query, args)64 rv = cur.fetchall()65 return (rv[0] if rv else None) if one else rv666768def get_user_id(username):69 """Convenience method to look up the id for a username."""57 rv = g.db.execute('select user_id from user where username = ?',58 [username]).fetchone()70 rv = query_db('select user_id from user where username = ?',71 [username], one=True)72 return rv[0] if rv else None737475def format_datetime(timestamp):
8 unmodified lines
848586@app.before_request87def before_request():75 """Make sure we are connected to the database each request and look76 up the current user so that we know he's there.77 """78 g.db = connect_db()88 g.user = None89 if 'user_id' in session:90 g.user = query_db('select * from user where user_id = ?',91 [session['user_id']], one=True)929385@app.teardown_request86def teardown_request(exception):87 """Closes the database again at the end of the request."""88 if hasattr(g, 'db'):89 g.db.close()909194@app.route('/')95def timeline():96 """Shows a users timeline or if no user is logged in it will97 redirect to the public timeline. This timeline shows the user's
48 unmodified lines
146 abort(401)147 whom_id = get_user_id(username)148 if whom_id is None:149 abort(404)150 db = get_db()148 g.db.execute('insert into follower (who_id, whom_id) values (?, ?)',149 [session['user_id'], whom_id])150 g.db.commit()151 db.execute('insert into follower (who_id, whom_id) values (?, ?)',152 [session['user_id'], whom_id])153 db.commit()154 flash('You are now following "%s"' % username)155 return redirect(url_for('user_timeline', username=username))156157
4 unmodified lines
162 abort(401)163 whom_id = get_user_id(username)164 if whom_id is None:165 abort(404)166 db = get_db()163 g.db.execute('delete from follower where who_id=? and whom_id=?',164 [session['user_id'], whom_id])165 g.db.commit()167 db.execute('delete from follower where who_id=? and whom_id=?',168 [session['user_id'], whom_id])169 db.commit()170 flash('You are no longer following "%s"' % username)171 return redirect(url_for('user_timeline', username=username))172173
2 unmodified lines
176 """Registers a new message for the user."""177 if 'user_id' not in session:178 abort(401)179 if request.form['text']:180 db = get_db()176 g.db.execute('''insert into message (author_id, text, pub_date)177 values (?, ?, ?)''', (session['user_id'], request.form['text'],178 int(time.time())))179 g.db.commit()181 db.execute('''insert into message (author_id, text, pub_date)182 values (?, ?, ?)''', (session['user_id'], request.form['text'],183 int(time.time())))184 db.commit()185 flash('Your message was recorded')186 return redirect(url_for('timeline'))187188
36 unmodified lines
225 error = 'The two passwords do not match'226 elif get_user_id(request.form['username']) is not None:227 error = 'The username is already taken'228 else:229 db = get_db()224 g.db.execute('''insert into user (225 username, email, pw_hash) values (?, ?, ?)''',226 [request.form['username'], request.form['email'],227 generate_password_hash(request.form['password'])])228 g.db.commit()230 db.execute('''insert into user (231 username, email, pw_hash) values (?, ?, ?)''',232 [request.form['username'], request.form['email'],233 generate_password_hash(request.form['password'])])234 db.commit()235 flash('You were successfully registered and can login now')236 return redirect(url_for('login'))237 return render_template('register.html', error=error)238
11 unmodified lines
250app.jinja_env.filters['gravatar'] = gravatar_url251252253if __name__ == '__main__':254 init_db()255 app.run()