Skip to content
Myr

db.py

This file

Path

examples/tutorial/flaskr/db.py

54 lines · 1.2 KiB · Python

Last changed by

Not known.

History of this file

Take it

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

Merge remote-tracking branch 'origin/1.1.x'David Lordbefore adoption909b975

lines 1–54why, one step back
1import sqlite3
23import click4from flask import current_app5from flask import g6from flask.cli import with_appcontext789def 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")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)