forked from wikispeedruns/wikipedia-speedruns
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdb.py
More file actions
54 lines (43 loc) · 1.17 KB
/
db.py
File metadata and controls
54 lines (43 loc) · 1.17 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
import pymysql
from flask import current_app, g
from contextlib import contextmanager
_instance_db = None
def init_app(app):
app.teardown_appcontext(close_db)
def get_conn_info():
return {
'user' : current_app.config["MYSQL_USER"],
'host' : current_app.config["MYSQL_HOST"],
'password' : current_app.config["MYSQL_PASSWORD"],
'database' : current_app.config['DATABASE']
}
# Keep up to date with scripts/schema.sql
def get_db_version():
return '2.4'
def get_db():
if _instance_db:
return _instance_db
if 'db' not in g:
g.db = pymysql.connect(**get_conn_info())
return g.db
def close_db(exception):
db = g.pop('db', None)
if db is not None:
db.close()
@contextmanager
def use_instance_db(conn={}):
"""
Usage:
with use_instance_db() as db:
do stuff with db
"""
if not conn:
# Needs to have app context if no conn info passed in
conn = get_conn_info()
try:
global _instance_db
_instance_db = pymysql.connect(**conn)
yield _instance_db
finally:
if _instance_db is not None:
_instance_db.close()