Skip to content
Myr

db.py

This file

Path

examples/tutorial/flaskr/db.py

53 lines · 1.2 KiB · Python

Last changed by

Merge pull request #3183 from singingwolfboy/pre-commitDavid Baumgoldbefore adoption1dda032

History of this file

Take it

1import 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"], detect_types=sqlite3.PARSE_DECLTYPES16        )17        g.db.row_factory = sqlite3.Row1819    return g.db202122def close_db(e=None):23    """If this request connected to the database, close the24    connection.25    """26    db = g.pop("db", None)2728    if db is not None:29        db.close()303132def init_db():33    """Clear existing data and create new tables."""34    db = get_db()3536    with current_app.open_resource("schema.sql") as f:37        db.executescript(f.read().decode("utf8"))383940@click.command("init-db")41@with_appcontext42def init_db_command():43    """Clear existing data and create new tables."""44    init_db()45    click.echo("Initialized the database.")464748def init_app(app):49    """Register database functions with the Flask app. This is called by50    the application factory.51    """52    app.teardown_appcontext(close_db)53    app.cli.add_command(init_db_command)