31 lines
961 B
Python
31 lines
961 B
Python
from sqlalchemy import create_engine
|
|
from sqlalchemy.orm import sessionmaker
|
|
|
|
class Database:
|
|
def __init__(self, connection_string: dict):
|
|
"""
|
|
connection_string ist ein Dictionary, z. B.:
|
|
{
|
|
"driver": "postgresql+psycopg2",
|
|
"username": "postgres",
|
|
"password": "mein_passwort",
|
|
"host": "localhost",
|
|
"port": 5432,
|
|
"database": "myapp"
|
|
}
|
|
"""
|
|
self.connection_string = connection_string
|
|
self.engine = self._create_engine()
|
|
self.SessionLocal = sessionmaker(bind=self.engine)
|
|
|
|
def _create_engine(self):
|
|
conn = self.connection_string
|
|
url = f"{conn['driver']}://{conn['username']}:{conn['password']}@{conn['host']}:{conn['port']}/{conn['database']}"
|
|
return create_engine(url, echo=True)
|
|
|
|
def get_engine(self):
|
|
return self.engine
|
|
|
|
def get_session(self):
|
|
return self.SessionLocal()
|