32 lines
826 B
Python
32 lines
826 B
Python
from os import environ
|
|
from collections import namedtuple
|
|
import pg8000
|
|
|
|
from flask import g
|
|
|
|
def db():
|
|
if not hasattr(g, 'db_connection'):
|
|
g.db_connection = pg8000.connect(
|
|
host=environ['DB_HOST'],
|
|
database=environ['DB_NAME'],
|
|
user=environ['DB_USER'],
|
|
password=environ['DB_PASSWORD'],
|
|
)
|
|
|
|
return g.db_connection
|
|
|
|
def query(querystring, **params):
|
|
try:
|
|
cursor = db().cursor()
|
|
cursor.paramstyle = "named"
|
|
cursor.execute(querystring, params)
|
|
db().commit()
|
|
return cursor
|
|
except:
|
|
db().rollback()
|
|
raise
|
|
|
|
def select(querystring, **params):
|
|
cursor = query(querystring, **params)
|
|
columns = [x[0] for x in cursor.description]
|
|
return [dict(zip(columns, row)) for row in cursor.fetchall()]
|