You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
44 lines
762 B
44 lines
762 B
3 years ago
|
import sqlite3
|
||
|
|
||
|
from flask import current_app, g
|
||
|
|
||
3 years ago
|
import os
|
||
3 years ago
|
DB_FILE = os.environ.get('DB_FILE', './data/db.sqlite')
|
||
3 years ago
|
|
||
3 years ago
|
get_return = sqlite3.Connection
|
||
|
|
||
3 years ago
|
|
||
3 years ago
|
def get() -> get_return:
|
||
3 years ago
|
if 'db' not in g:
|
||
|
g.db = sqlite3.connect(
|
||
|
DB_FILE,
|
||
|
detect_types=sqlite3.PARSE_DECLTYPES,
|
||
|
)
|
||
|
g.db.row_factory = sqlite3.Row
|
||
|
|
||
|
return g.db
|
||
|
|
||
3 years ago
|
|
||
3 years ago
|
def close(e=None):
|
||
|
db = g.pop('db', None)
|
||
|
|
||
|
if db:
|
||
|
db.close()
|
||
|
|
||
3 years ago
|
|
||
3 years ago
|
def init():
|
||
|
db = get()
|
||
|
|
||
|
with current_app.open_resource('init.sql') as f:
|
||
|
db.executescript(f.read().decode('utf8'))
|
||
|
db.commit()
|
||
|
|
||
3 years ago
|
|
||
3 years ago
|
def init_app(app):
|
||
|
app.teardown_appcontext(close)
|
||
|
|
||
|
import os.path
|
||
|
if not os.path.exists(DB_FILE):
|
||
|
with app.app_context():
|
||
|
init()
|