jukebox-software/database.py

47 lines
1.3 KiB
Python

import os
import psycopg2
DB_ADDRESS = os.getenv('DB_ADDRESS', 'localhost')
DB_PORT = os.getenv('DB_PORT', 5432)
DB_USER = os.getenv('DB_USER', 'postgres')
DB_PASSWORD = os.getenv('DB_PASSWORD', '')
DB_NAME = os.getenv('DB_NAME', 'postgres')
class DBConnector:
"""Context managed database class. Use with statements to automatically open and close the database connection, like
so:
.. code-block:: python
with DBConnector() as db:
db.read()
"""
def __enter__(self):
self.conn = psycopg2.connect()
self.cur = self.conn.cursor()
def __exit__(self):
self.cur.close()
self.conn.close()
def _query(self, sql):
try:
self.cur.execute(sql)
result = self.cur.fetchall()
except psycopg2.DatabaseError as e:
result = []
return result
def read(self, **kwargs):
"""Read rows from a database that match the specified filters.
:param kwargs: Column constraints; i.e. what value to filter by in what column.
:returns: A list of dictionaries of all matching rows, or an empty list if no match."""
pass
def write(self, **kwargs):
"""Write a row to the database.
:param kwargs: Values to write for each database; specify each column separately!"""
pass