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
Provenance
- Commit
c2e5799- Tree
14ca11c- Author
Armin Ronacher <armin.ronacher@active-4.com>- Committer
Armin Ronacher <armin.ronacher@active-4.com>- Parent
3e9f4e2
4 files changed+169 added−104 removed
modified:docs/patterns/sqlite3.rst+59 added-48 removed
1 unmodified line2 3 Using SQLite 3 with Flask4 =========================5 6-In Flask you can implement the opening of database connections at the7-beginning of the request and closing at the end with the8-:meth:`~flask.Flask.before_request` and :meth:`~flask.Flask.teardown_request`9-decorators in combination with the special :class:`~flask.g` object.6+In Flask you can implement the opening of database connections on demand7+and closing it when the context dies (usually at the end of the request)8+easily.9 11-So here is a simple example of how you can use SQLite 3 with Flask::10+Here is a simple example of how you can use SQLite 3 with Flask::11 12 import sqlite314- from flask import g13+ from flask import _app_ctx_stack14 15 DATABASE = '/path/to/database.db'16 18- 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_db22 21- @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()28 25- @app.teardown_request26- def teardown_request(exception):27- if hasattr(g, 'db'):28- g.db.close()29+All the application needs to do in order to now use the database is having30+an active application context (which is always true if there is an request31+in flight) or to create an application context itself. At that point the32+``get_db`` function can be used to get the current database connection.33+Whenever the context is destroyed the database connection will be34+terminated.35 36+Example::37+38+ @app.route('/')39+ def index():40+ cur = get_db().cursor()41+ ...42+43+44 .. note::45 32- 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.50 51 Connect on Demand52 -----------------53 40-The downside of this approach is that this will only work if Flask41-executed the before-request handlers for you. If you are attempting to42-use the database from a script or the interactive Python shell you would43-have to do something like this::54+The upside of this approach (connecting on first use) is that this will55+only opening the connection if truly necessary. If you want to use this56+code outside a request context you can use it in a Python shell by opening57+the application context by hand::58 45- 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()61 49-In order to trigger the execution of the connection code. You won't be50-able to drop the dependency on the request context this way, but you could51-make it so that the application connects when necessary::52-53- def get_connection():54- db = getattr(g, '_db', None)55- if db is None:56- db = g._db = connect_db()57- return db58-59-Downside here is that you have to use ``db = get_connection()`` instead of60-just being able to use ``g.db`` directly.61-62 .. _easy-querying:63 64 Easy Querying65 -------------66 67 Now in each request handling function you can access `g.db` to get the68 current open database connection. To simplify working with SQLite, a69-helper function can be useful::69+row factory function is useful. It is executed for every result returned70+from the database to convert the result. For instance in order to get71+dictionaries instead of tuples this can be used::72 73+ def make_dicts(cursor, row):74+ return dict((cur.description[idx][0], value)75+ for idx, value in enumerate(row))76+77+ db.row_factory = make_dicts78+79+Additionally it is a good idea to provide a query function that combines80+getting 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 rv87 77-This handy little function makes working with the database much more78-pleasant than it is by just using the raw cursor and connection objects.88+This handy little function in combination with a row factory makes working89+with the database much more pleasant than it is by just using the raw90+cursor and connection objects.91 92 Here is how you can use it::93 94 for user in query_db('select * from users'):21 unmodified lines116 `schema.sql` file that creates the database. It's a good idea to provide117 a function that creates the database based on that schema. This function118 can do that for you::119 108- 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 linesmodified:docs/appcontext.rst+44 added
83 unmodified lines84 Extensions are free to store additional information on the topmost level,85 assuming they pick a sufficiently unique name.86 87 For more information about that, see :ref:`extension-dev`.88+89+Context Usage90+-------------91+92+The context is typically used to cache resources on there that need to be93+created on a per-request or usage case. For instance database connects94+are destined to go there. When storing things on the application context95+unique names should be chosen as this is a place that is shared between96+Flask applications and extensions.97+98+The most common usage is to split resource management into two parts:99+100+1. an implicit resource caching on the context.101+2. a context teardown based resource deallocation.102+103+Generally there would be a ``get_X()`` function that creates resource104+``X`` if it does not exist yet and otherwise returns the same resource,105+and a ``teardown_X()`` function that is registered as teardown handler.106+107+This is an example that connects to a database::108+109+ import sqlite3110+ from flask import _app_ctx_stack111+112+ def get_db():113+ top = _app_ctx_stack.top114+ if not hasattr(top, 'database'):115+ top.database = connect_to_database()116+ return top.database117+118+ @app.teardown_appcontext119+ def teardown_db(exception):120+ top = _app_ctx_stack.top121+ if hasattr(top, 'database'):122+ top.database.close()123+124+The first time ``get_db()`` is called the connection will be established.125+To make this implicit a :class:`~werkzeug.local.LocalProxy` can be used::126+127+ from werkzeug.local import LocalProxy128+ db = LocalProxy(get_db)129+130+That way a user can directly access ``db`` which internally calls131+``get_db()``.modified:examples/flaskr/flaskr.py+22 added-19 removed
9 unmodified lines10 :license: BSD, see LICENSE for more details.11 """12 from __future__ import with_statement13 from sqlite3 import dbapi2 as sqlite314-from contextlib import closing14 from flask import Flask, request, session, g, redirect, url_for, abort, \16- render_template, flash15+ render_template, flash, _app_ctx_stack16 17 # configuration18 DATABASE = '/tmp/flaskr.db'19 DEBUG = True6 unmodified lines26 app.config.from_object(__name__)27 app.config.from_envvar('FLASKR_SETTINGS', silent=True)28 29 31-def connect_db():32- """Returns a new connection to the database."""33- return sqlite3.connect(app.config['DATABASE'])34-35-30 def 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()37 38 44-@app.before_request45-def before_request():46- """Make sure we are connected to the database each request."""47- g.db = connect_db()39+def 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_db47 48 50-@app.teardown_request51-def teardown_request(exception):49+@app.teardown_appcontext50+def 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()55 56 57 @app.route('/')58 def 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)63 64 65 @app.route('/add', methods=['POST'])66 def 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'))75 76 19 unmodified lines96 return redirect(url_for('show_entries'))97 98 99 if __name__ == '__main__':100+ init_db()101 app.run()modified:examples/minitwit/minitwit.py+44 added-37 removed
11 unmodified lines12 import time13 from sqlite3 import dbapi2 as sqlite314 from hashlib import md515 from datetime import datetime16-from contextlib import closing16 from flask import Flask, request, session, url_for, redirect, \18- render_template, abort, g, flash17+ render_template, abort, g, flash, _app_ctx_stack18 from werkzeug import check_password_hash, generate_password_hash19 20 21 # configuration7 unmodified lines29 app.config.from_object(__name__)30 app.config.from_envvar('MINITWIT_SETTINGS', silent=True)31 32 34-def connect_db():35- """Returns a new connection to the database."""36- return sqlite3.connect(app.config['DATABASE'])33+def 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_db42 43 44+@app.teardown_appcontext45+def 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()50+51+52 def 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()59 60 61 def 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 rv66 67 68 def 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 None73 74 75 def format_datetime(timestamp):8 unmodified lines84 85 86 @app.before_request87 def 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)92 93 85-@app.teardown_request86-def teardown_request(exception):87- """Closes the database again at the end of the request."""88- if hasattr(g, 'db'):89- g.db.close()90-91-94 @app.route('/')95 def 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's48 unmodified lines146 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))156 157 4 unmodified lines162 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))172 173 2 unmodified lines176 """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'))187 188 36 unmodified lines225 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 lines250 app.jinja_env.filters['gravatar'] = gravatar_url251 252 253 if __name__ == '__main__':254+ init_db()255 app.run()