Spaces:
Running
Running
improve db connection functions
Browse files- src/repository/common.py +9 -5
src/repository/common.py
CHANGED
|
@@ -1,6 +1,6 @@
|
|
| 1 |
from typing import Generator
|
| 2 |
from sqlalchemy import create_engine
|
| 3 |
-
from sqlalchemy.orm import sessionmaker
|
| 4 |
from contextlib import contextmanager
|
| 5 |
|
| 6 |
from dotenv import load_dotenv
|
|
@@ -8,15 +8,19 @@ import os
|
|
| 8 |
|
| 9 |
load_dotenv()
|
| 10 |
|
| 11 |
-
|
| 12 |
-
|
| 13 |
-
|
|
|
|
|
|
|
| 14 |
|
| 15 |
@contextmanager
|
| 16 |
-
def get_session() -> Generator:
|
| 17 |
"""
|
| 18 |
Get a connection to the Postgres database
|
| 19 |
"""
|
|
|
|
|
|
|
| 20 |
db = SessionLocal()
|
| 21 |
try:
|
| 22 |
yield db
|
|
|
|
| 1 |
from typing import Generator
|
| 2 |
from sqlalchemy import create_engine
|
| 3 |
+
from sqlalchemy.orm import sessionmaker, Session
|
| 4 |
from contextlib import contextmanager
|
| 5 |
|
| 6 |
from dotenv import load_dotenv
|
|
|
|
| 8 |
|
| 9 |
load_dotenv()
|
| 10 |
|
| 11 |
+
def get_engine():
|
| 12 |
+
database_url = os.getenv("DATABASE_URL")
|
| 13 |
+
if not database_url:
|
| 14 |
+
raise ValueError("DATABASE_URL is not set in environment variables")
|
| 15 |
+
return create_engine(database_url)
|
| 16 |
|
| 17 |
@contextmanager
|
| 18 |
+
def get_session() -> Generator[Session, None, None]:
|
| 19 |
"""
|
| 20 |
Get a connection to the Postgres database
|
| 21 |
"""
|
| 22 |
+
engine = get_engine()
|
| 23 |
+
SessionLocal = sessionmaker(bind=engine)
|
| 24 |
db = SessionLocal()
|
| 25 |
try:
|
| 26 |
yield db
|