db.py
This file
Path
examples/tutorial/flaskr/db.py
54 lines · 1.2 KiB · Python
Last changed by
Merge pull request #2676 from davidism/tutorialDavid Lordbefore adoptionc3e2ff2
History of this fileTake it
Merge pull request #2676 from davidism/tutorialDavid Lordbefore adoptionc3e2ff2
lines 1–54why, one step back1import sqlite323import click4from flask import current_app, g5from flask.cli import with_appcontext678def get_db():9 """Connect to the application's configured database. The connection10 is unique for each request and will be reused if this is called11 again.12 """13 if 'db' not in g:14 g.db = sqlite3.connect(15 current_app.config['DATABASE'],16 detect_types=sqlite3.PARSE_DECLTYPES17 )18 g.db.row_factory = sqlite3.Row1920 return g.db212223def close_db(e=None):24 """If this request connected to the database, close the25 connection.26 """27 db = g.pop('db', None)2829 if db is not None:30 db.close()313233def init_db():34 """Clear existing data and create new tables."""35 db = get_db()3637 with current_app.open_resource('schema.sql') as f:38 db.executescript(f.read().decode('utf8'))394041@click.command('init-db')42@with_appcontext43def init_db_command():44 """Clear existing data and create new tables."""45 init_db()46 click.echo('Initialized the database.')474849def init_app(app):50 """Register database functions with the Flask app. This is called by51 the application factory.52 """53 app.teardown_appcontext(close_db)54 app.cli.add_command(init_db_command)