46 lines
1.2 KiB
Python
46 lines
1.2 KiB
Python
import os
|
|
import psycopg2
|
|
|
|
DB_ADDRESS = os.environ['DB_ADDRESS']
|
|
DB_USER = os.environ['DB_USER']
|
|
DB_PASSWORD = os.environ['DB_PASSWORD']
|
|
DB_NAME = os.environ['DB_NAME']
|
|
|
|
|
|
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 |