Skip to content
Myr

db.py

This file

Path

examples/tutorial/flaskr/db.py

52 lines · 1.2 KiB · Python

Last changed by

Merge pull request #4647 from pallets/cli-app_contextDavid Lordbefore adoptioncec5f74

History of this file

Take it

The walk stopped after 200 commits: lines older than 01e804a point at it.

Merge pull request #4184 from pallets/dependabot/pip/sphinx-tabs-3.1.0Grey Libefore adoption01e804a

lines 1–52why, one step back
1import sqlite3
23import click4from flask import current_app5from flask import g678def 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")41def init_db_command():42 """Clear existing data and create new tables."""43 init_db()44 click.echo("Initialized the database.")454647def init_app(app):48 """Register database functions with the Flask app. This is called by49 the application factory.50 """51 app.teardown_appcontext(close_db)52 app.cli.add_command(init_db_command)