|
@@ -0,0 +1,38 @@
|
|
1
|
+import sqlite3
|
|
2
|
+
|
|
3
|
+import click
|
|
4
|
+from flask import current_app, g
|
|
5
|
+from flask.cli import with_appcontext
|
|
6
|
+
|
|
7
|
+def get_db():
|
|
8
|
+ if 'db' not in g:
|
|
9
|
+ g.db = sqlite3.connect(
|
|
10
|
+ current_app.config['DATABASE'],
|
|
11
|
+ detect_types=sqlite3.PARSE_DECLTYPES
|
|
12
|
+ )
|
|
13
|
+ g.db.row_factory = sqlite3.Row
|
|
14
|
+
|
|
15
|
+ return g.db
|
|
16
|
+
|
|
17
|
+def close_db(e=None):
|
|
18
|
+ db = g.pop('db', None)
|
|
19
|
+
|
|
20
|
+ if db is not None:
|
|
21
|
+ db.close()
|
|
22
|
+
|
|
23
|
+def init_db():
|
|
24
|
+ db = get_db()
|
|
25
|
+
|
|
26
|
+ with current_app.open_resource('schema.sql') as f:
|
|
27
|
+ db.executescript(f.read().decode('utf8'))
|
|
28
|
+
|
|
29
|
+@click.command('init-db')
|
|
30
|
+@with_appcontext
|
|
31
|
+def init_db_command():
|
|
32
|
+ init_db()
|
|
33
|
+ click.echo('Initialized the database.')
|
|
34
|
+
|
|
35
|
+def init_app(app):
|
|
36
|
+ app.teardown_appcontext(close_db)
|
|
37
|
+ app.cli.add_command(init_db_command)
|
|
38
|
+
|