2018-10-26 18:14:27 +02:00
|
|
|
from .config import DATABASE_NAME
|
|
|
|
from .config import DATABASE_USER
|
|
|
|
from .config import DATABASE_PASS
|
|
|
|
from .config import DATABASE_HOST
|
2018-11-03 21:40:45 +01:00
|
|
|
from .config import DATABASE_PORT
|
2018-11-10 22:58:58 +01:00
|
|
|
import falcon
|
2018-11-03 22:55:23 +01:00
|
|
|
import psycopg2
|
|
|
|
import psycopg2.extras
|
|
|
|
|
2018-09-24 23:49:47 +02:00
|
|
|
|
2018-11-07 16:41:21 +01:00
|
|
|
class DatabaseManager():
|
|
|
|
'''Manage database connection.'''
|
2018-09-23 23:00:05 +02:00
|
|
|
|
2018-11-07 16:41:21 +01:00
|
|
|
def __init__(self):
|
|
|
|
self._connection_uri = 'dbname={} user={} password={} host={} port={}'.format(DATABASE_NAME, DATABASE_USER, DATABASE_PASS, DATABASE_HOST, DATABASE_PORT)
|
|
|
|
|
|
|
|
def __enter__(self):
|
2018-11-10 22:58:58 +01:00
|
|
|
try:
|
|
|
|
self._connection = psycopg2.connect(self._connection_uri, cursor_factory=psycopg2.extras.DictCursor)
|
|
|
|
except psycopg2.OperationalError:
|
|
|
|
title = '500 Internal Server Error'
|
|
|
|
description = 'Could not connect to database'
|
|
|
|
raise falcon.HTTPInternalServerError(title, description)
|
|
|
|
|
2018-11-07 16:41:21 +01:00
|
|
|
return self._connection
|
|
|
|
|
|
|
|
def __exit__(self, exc_type, exc_value, exc_traceback):
|
|
|
|
self._connection.close()
|
2018-09-23 23:00:05 +02:00
|
|
|
|
2018-09-23 15:47:00 +02:00
|
|
|
# vim: set sw=4 ts=4 expandtab:
|