db.py
This file
Path
examples/tutorial/flaskr/db.py
56 lines · 1.3 KiB · Python
Last changed by
Merge remote-tracking branch 'origin/stable'David Lordbefore adoption22c48a7
History of this fileTake it
1import sqlite32from datetime import datetime34import click5from flask import current_app6from flask import g789def get_db():10 """Connect to the application's configured database. The connection11 is unique for each request and will be reused if this is called12 again.13 """14 if "db" not in g:15 g.db = sqlite3.connect(16 current_app.config["DATABASE"], 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")42def init_db_command():43 """Clear existing data and create new tables."""44 init_db()45 click.echo("Initialized the database.")464748sqlite3.register_converter("timestamp", lambda v: datetime.fromisoformat(v.decode()))495051def init_app(app):52 """Register database functions with the Flask app. This is called by53 the application factory.54 """55 app.teardown_appcontext(close_db)56 app.cli.add_command(init_db_command)