import sqlite3 import click # From https://flask.palletsprojects.com/en/3.0.x/tutorial/database/ from flask import current_app, g # Apparently g is a sort of a general per-request bucket, so that # multiple parallel requests won't collide. # Initializes the connection and stores it in g. def get_db(): if 'db' not in g: g.db = sqlite3.connect( current_app.config['DATABASE'], detect_types=sqlite3.PARSE_DECLTYPES ) # g.db.row_factory = sqlite3.Row return g.db # Close and remove from g. def close_db(e=None): db = g.pop('db', None) if db is not None: db.close() # This iniitalizes the database. Will empty our table if called. def init_db(): db = get_db() with current_app.open_resource('schema.sql') as f: db.executescript(f.read().decode('utf8')) # Not sure what this is. Seems to tie it to a command on flask command line. @click.command('init-db') def init_db_command(): """Clear the existing data and create new tables.""" #from __init__ import create_app #app = create_app() #with app.app_context(): init_db() click.echo('Initialized the database.') # This is to be called by the factory. It adds the operations to the # context to be called automatically. def init_app(app): app.teardown_appcontext(close_db) app.cli.add_command(init_db_command)