-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathdatabase.py
44 lines (32 loc) · 1009 Bytes
/
database.py
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
import app
from sqlalchemy import *
from sqlalchemy.dialects.mysql import *
from sqlalchemy.orm import sessionmaker
from sqlalchemy.ext.declarative import declarative_base
import sys
TableBase = declarative_base()
engine = create_engine(app.app.config['DATABASE_URI'])
DBSession = sessionmaker(bind=engine)
if 'app' in sys.modules:
print('database imported in flask')
from flask import g
from app import app
def get_session():
s = getattr(g, '_dbsession', None)
if s is None:
s = g._dbsession = DBSession()
print('new session')
else:
print('get session')
return s
@app.teardown_appcontext
def teardown_session(exception):
s = getattr(g, '_dbsession', None)
if s is not None:
s.close()
print('close session')
from werkzeug.local import LocalProxy
session = LocalProxy(get_session)
else:
print('database imported outside flask')
session = DBSession()