]> git.datanom.net - liogui.git/blob - webapp/db.py
Completed User Administration
[liogui.git] / webapp / db.py
1 import sqlite3
2 from datetime import datetime
3
4 import click
5 from flask import current_app, g
6
7 def init_db():
8 db = get_db()
9
10 with current_app.open_resource('schema.sql') as f:
11 db.executescript(f.read().decode('utf8'))
12
13 @click.command('init-db')
14 def init_db_command():
15 """Clear the existing data and create new tables."""
16 init_db()
17 click.echo('Initialized the database.')
18
19 sqlite3.register_converter(
20 "timestamp", lambda v: datetime.fromisoformat(v.decode())
21 )
22
23 def init_app(app):
24 app.teardown_appcontext(close_db)
25 app.cli.add_command(init_db_command)
26
27 def get_db():
28 if 'db' not in g:
29 g.db = sqlite3.connect(
30 current_app.config['DATABASE'],
31 detect_types=sqlite3.PARSE_DECLTYPES
32 )
33 g.db.row_factory = sqlite3.Row
34
35 return g.db
36
37
38 def close_db(e=None):
39 db = g.pop('db', None)
40
41 if db is not None:
42 db.close()
43
This page took 0.914958 seconds and 6 git commands to generate.