-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathpostgres.py
44 lines (36 loc) · 1.04 KB
/
postgres.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
"""
Postgres module
"""
import psycopg2
from flask import g
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
from views import application
def get_db():
if "db" not in g:
g.db = psycopg2.connect(
host=application.config["DB_HOST"],
database=application.config["DB_DATABASE"],
user=application.config["DB_USER"],
password=application.config["DB_PASSWORD"],
)
return g.db
def get_db_session():
"""
Opens a new database connection if there is none yet for the
current application context.
"""
if not hasattr(g, "dbsession"):
engine = create_engine(application.config["SQLALCHEMY_DATABASE_URI"], echo=True)
engine.connect()
DbSession = sessionmaker(bind=engine)
DbSession.configure(bind=engine)
g.dbsession = DbSession()
return g.dbsession
def close_db():
adb = g.pop("db", None)
if adb is not None:
adb.close()
def postgres_cursor():
cursor = get_db().cursor()
return cursor