33 lines
783 B
Python
33 lines
783 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(
|
|
database=environ['DB_NAME'],
|
|
user=environ['DB_USER'],
|
|
password=environ['DB_PASSWORD'],
|
|
)
|
|
|
|
return g.db_connection
|
|
|
|
def query(query, **params):
|
|
try:
|
|
cursor = db().cursor()
|
|
cursor.paramstyle = "named"
|
|
cursor.execute(query, params)
|
|
db().commit()
|
|
|
|
columns = [x[0] for x in cursor.description]
|
|
rows = [dict(zip(columns, row)) for row in cursor.fetchall()]
|
|
|
|
return DBResult(
|
|
rows=rows,
|
|
rowcount=cursor.rowcount,
|
|
)
|
|
except:
|
|
db().rollback()
|
|
raise
|