diff options
author | ubq323 <ubq323> | 2021-05-21 16:34:45 +0000 |
---|---|---|
committer | ubq323 <ubq323> | 2021-05-21 16:34:45 +0000 |
commit | bab4893709e736e30f208a810b46d21aed6cef0e (patch) | |
tree | 409bdbd25206051f0762fafb75311bba6ac9afde | |
parent | c8681bb17437e316c82f89c792458cda019ba74e (diff) |
database infrastructure
-rw-r--r-- | .fossil-settings/ignore-glob | 1 | ||||
-rw-r--r-- | apioforum/__init__.py | 9 | ||||
-rw-r--r-- | apioforum/db.py | 40 |
3 files changed, 50 insertions, 0 deletions
diff --git a/.fossil-settings/ignore-glob b/.fossil-settings/ignore-glob index f166c18..8c284f4 100644 --- a/.fossil-settings/ignore-glob +++ b/.fossil-settings/ignore-glob @@ -1,2 +1,3 @@ venv/* +*.db *.py[cod] diff --git a/apioforum/__init__.py b/apioforum/__init__.py index 0ea397f..6d4e53d 100644 --- a/apioforum/__init__.py +++ b/apioforum/__init__.py @@ -2,12 +2,21 @@ # yay from flask import Flask +from .db import get_db def create_app(): app = Flask(__name__) + from . import db + db.init_app(app) + @app.route("/") def main(): return "the" + @app.route("/b") + def b(): + db=get_db() + return str(db.execute("select 2 + 2;").fetchone()[0]) + return app diff --git a/apioforum/db.py b/apioforum/db.py new file mode 100644 index 0000000..be2d7e0 --- /dev/null +++ b/apioforum/db.py @@ -0,0 +1,40 @@ +import sqlite3 +import click +from flask import current_app, g +from flask.cli import with_appcontext + +def get_db(): + if 'db' not in g: + g.db = sqlite3.connect('database.db',detect_types=sqlite3.PARSE_DECLTYPES) + g.db.row_factory = sqlite3.Row + g.db.execute("PRAGMA foreighn_keys = ON;") + return g.db + +def close_db(e=None): + db = g.pop('db', None) + if db is not None: + db.close() + +migrations = [ +] + +def init_db(): + db = get_db() + version = db.execute("PRAGMA user_version;").fetchone()[0] + for i in range(version, len(migrations)): + db.executescript(migrations[i]) + db.execute(f"PRAGMA user_version = {i+1}") + db.commit() + click.echo(f"migration {i}") + +@click.command("migrate") +@with_appcontext +def migrate_command(): + """update database scheme etc""" + init_db() + click.echo("ok") + +def init_app(app): + app.teardown_appcontext(close_db) + app.cli.add_command(migrate_command) + |