2021-03-22 12:42:42 +01:00
|
|
|
# SPDX-License-Identifier: GPL-3.0-only
|
|
|
|
|
2018-11-10 22:58:58 +01:00
|
|
|
import falcon
|
2018-11-03 22:55:23 +01:00
|
|
|
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,
|
|
|
|
)
|
|
|
|
|
2018-09-24 23:49:47 +02:00
|
|
|
|
2019-11-27 11:30:06 +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):
|
2020-03-02 10:24:29 +01:00
|
|
|
self._connection_uri = f"dbname={DATABASE_NAME} user={DATABASE_USER} password={DATABASE_PASS} host={DATABASE_HOST} port={DATABASE_PORT}"
|
2018-11-07 16:41:21 +01:00
|
|
|
|
|
|
|
def __enter__(self):
|
2018-11-10 22:58:58 +01:00
|
|
|
try:
|
2019-11-27 11:30:06 +01:00
|
|
|
self._connection = psycopg2.connect(
|
|
|
|
self._connection_uri, cursor_factory=psycopg2.extras.DictCursor
|
|
|
|
)
|
2018-11-10 22:58:58 +01:00
|
|
|
except psycopg2.OperationalError:
|
2019-11-27 11:30:06 +01:00
|
|
|
title = "500 Internal Server Error"
|
|
|
|
description = "Could not connect to database"
|
2018-11-10 22:58:58 +01:00
|
|
|
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
|
|
|
|
2019-11-27 11:30:06 +01:00
|
|
|
|
2018-09-23 15:47:00 +02:00
|
|
|
# vim: set sw=4 ts=4 expandtab:
|