Skip to content

Commit cf46ba6

Browse files
committed
Add database utility
1 parent 8fd2136 commit cf46ba6

File tree

1 file changed

+28
-0
lines changed

1 file changed

+28
-0
lines changed

database.py

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
"""SQLAlchemy DB Engine for FastAPI dependency injection."""
2+
3+
import sqlalchemy
4+
from sqlalchemy.orm import Session
5+
from settings import getenv
6+
7+
8+
def _engine_str(name: str = getenv("DB_NAME")) -> str:
9+
"""Helper function for reading settings from environment variables to produce connection string."""
10+
dialect = "postgresql+psycopg2"
11+
user = getenv("DB_USERNAME")
12+
password = getenv("DB_PASSWORD")
13+
host = getenv("DB_HOST")
14+
port = getenv("DB_PORT")
15+
return f"{dialect}://{user}:{password}@{host}:{port}/{name}"
16+
17+
18+
engine = sqlalchemy.create_engine(_engine_str(), echo=True)
19+
"""Application-level SQLAlchemy database engine."""
20+
21+
22+
def db_session():
23+
"""Generator function offering dependency injection of SQLAlchemy Sessions."""
24+
session = Session(engine)
25+
try:
26+
yield session
27+
finally:
28+
session.close()

0 commit comments

Comments
 (0)