44 lines
1.0 KiB
Python
44 lines
1.0 KiB
Python
import sqlite3
|
|
|
|
import click
|
|
from flask import current_app, g
|
|
from flask.cli import with_appcontext
|
|
|
|
|
|
def get_db(mod_path=None):
|
|
if 'db' not in g:
|
|
# provide modified path if is not None
|
|
if mod_path is None:
|
|
path=current_app.config["DATABASE_URI"]
|
|
else:
|
|
path=mod_path
|
|
g.db = sqlite3.connect(
|
|
path,
|
|
detect_types=sqlite3.PARSE_DECLTYPES
|
|
)
|
|
g.db.row_factory = sqlite3.Row
|
|
|
|
return g.db
|
|
|
|
def close_db(e=None):
|
|
db = g.pop('db', None)
|
|
|
|
if db is not None:
|
|
db.close()
|
|
|
|
|
|
@click.command('init-db')
|
|
@with_appcontext
|
|
def init_db_command():
|
|
"""Clear the existing data and create new tables."""
|
|
path = "./users.db"
|
|
db = get_db(mod_path="users.db")
|
|
|
|
with current_app.open_resource('schema.sql') as f:
|
|
db.executescript(f.read().decode('utf8'))
|
|
|
|
click.echo('Initialized the database at %s. Copy it to the according directory.'% path)
|
|
|
|
def init_app(app):
|
|
app.teardown_appcontext(close_db)
|
|
app.cli.add_command(init_db_command) |