-
Notifications
You must be signed in to change notification settings - Fork 10
Expand file tree
/
Copy pathdb.py
More file actions
69 lines (54 loc) · 1.54 KB
/
db.py
File metadata and controls
69 lines (54 loc) · 1.54 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
import argparse
import sqlite3
from flask import g
_DATABASE = "mugsy"
def bootstrap_data():
conn = None
try:
conn = sqlite3.connect("db/{}.db".format(_DATABASE))
with open("db/bootstrap.sql", "r") as f:
conn.executescript(f.read())
print("Bootstrapped data.")
except sqlite3.Error as e:
print(e)
finally:
if conn:
conn.close()
def init_db(app):
with app.app_context():
db = get_db()
with app.open_resource("db/schema.sql", mode="r") as f:
db.cursor().executescript(f.read())
db.commit()
def get_db():
db = getattr(g, "_database", None)
if db is None:
db = g._database = sqlite3.connect("db/{}.db".format(_DATABASE))
return db
def close_connection():
db = getattr(g, "_database", None)
if db is not None:
db.close()
def _init_db():
conn = None
try:
conn = sqlite3.connect("db/{}.db".format(_DATABASE))
with open("db/schema.sql", "r") as f:
conn.executescript(f.read())
print("Created sqlite database and schema.")
except sqlite3.Error as e:
print(e)
finally:
if conn:
conn.close()
if __name__ == "__main__":
parser = argparse.ArgumentParser(description="Create and bootstrap database.")
parser.add_argument(
"--bootstrap",
action="store_true",
help="Bootstrap data provided in bootstrap.sql",
)
args = parser.parse_args()
_init_db()
if args.bootstrap:
bootstrap_data()