1
0
mirror of https://github.com/ilri/dspace-statistics-api.git synced 2024-11-18 12:27:04 +01:00
dspace-statistics-api/dspace_statistics_api/database.py

39 lines
1004 B
Python
Raw Normal View History

import falcon
import psycopg2
import psycopg2.extras
2019-11-27 11:31:04 +01:00
from .config import (
DATABASE_HOST,
DATABASE_NAME,
DATABASE_PASS,
DATABASE_PORT,
DATABASE_USER,
)
2019-11-27 11:30:06 +01:00
class DatabaseManager:
"""Manage database connection."""
def __init__(self):
2019-11-27 11:30:06 +01:00
self._connection_uri = "dbname={} user={} password={} host={} port={}".format(
DATABASE_NAME, DATABASE_USER, DATABASE_PASS, DATABASE_HOST, DATABASE_PORT
)
def __enter__(self):
try:
2019-11-27 11:30:06 +01:00
self._connection = psycopg2.connect(
self._connection_uri, cursor_factory=psycopg2.extras.DictCursor
)
except psycopg2.OperationalError:
2019-11-27 11:30:06 +01:00
title = "500 Internal Server Error"
description = "Could not connect to database"
raise falcon.HTTPInternalServerError(title, description)
return self._connection
def __exit__(self, exc_type, exc_value, exc_traceback):
self._connection.close()
2019-11-27 11:30:06 +01:00
# vim: set sw=4 ts=4 expandtab: