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 fileTake it
Merge pull request #2676 from davidism/tutorialDavid Lordbefore adoptionc3e2ff2
lines 1–12why, 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 """Merge pull request #3183 from singingwolfboy/pre-commitDavid Baumgoldbefore adoption1dda032
line 13why, one step back13 if "db" not in g:Merge pull request #2676 from davidism/tutorialDavid Lordbefore adoptionc3e2ff2
line 14why, one step back14 g.db = sqlite3.connect(Merge pull request #3183 from singingwolfboy/pre-commitDavid Baumgoldbefore adoption1dda032
line 15why, one step back15 current_app.config["DATABASE"], detect_types=sqlite3.PARSE_DECLTYPESMerge pull request #2676 from davidism/tutorialDavid Lordbefore adoptionc3e2ff2
lines 16–25why, one step back16 )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 """Merge pull request #3183 from singingwolfboy/pre-commitDavid Baumgoldbefore adoption1dda032
line 26why, one step back26 db = g.pop("db", None)Merge pull request #2676 from davidism/tutorialDavid Lordbefore adoptionc3e2ff2
lines 27–35why, one step back2728 if db is not None:29 db.close()303132def init_db():33 """Clear existing data and create new tables."""34 db = get_db()35Merge pull request #3183 from singingwolfboy/pre-commitDavid Baumgoldbefore adoption1dda032
lines 36–37why, one step back36 with current_app.open_resource("schema.sql") as f:37 db.executescript(f.read().decode("utf8"))Merge pull request #2676 from davidism/tutorialDavid Lordbefore adoptionc3e2ff2
lines 38–39why, one step back3839Merge pull request #3183 from singingwolfboy/pre-commitDavid Baumgoldbefore adoption1dda032
line 40why, one step back40@click.command("init-db")Merge pull request #2676 from davidism/tutorialDavid Lordbefore adoptionc3e2ff2
lines 41–44why, one step back41@with_appcontext42def init_db_command():43 """Clear existing data and create new tables."""44 init_db()Merge pull request #3183 from singingwolfboy/pre-commitDavid Baumgoldbefore adoption1dda032
line 45why, one step back45 click.echo("Initialized the database.")Merge pull request #2676 from davidism/tutorialDavid Lordbefore adoptionc3e2ff2
lines 46–53why, one step back464748def 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)