-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdatabase.py
More file actions
41 lines (31 loc) · 1.1 KB
/
Copy pathdatabase.py
File metadata and controls
41 lines (31 loc) · 1.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
"""SQLAlchemy DB Engine for FastAPI dependency injection."""
import sqlalchemy
from sqlalchemy.orm import Session
from utils import getenv, getenv_bool
def _engine_str() -> str:
"""
Helper function for reading settings from environment variables to produce connection string.
Returns:
str: The connection string for the database.
"""
dialect = "postgresql+psycopg2"
user = getenv("DB_USERNAME")
password = getenv("DB_PASSWORD")
host = getenv("DB_HOST")
port = getenv("DB_PORT")
name = getenv("DB_NAME")
return f"{dialect}://{user}:{password}@{host}:{port}/{name}"
# Application-level SQLAlchemy database engine. SQL statement logging would
# include device tokens, so it is opt-in via DB_ECHO for local debugging only.
engine = sqlalchemy.create_engine(_engine_str(), echo=getenv_bool("DB_ECHO"))
def db_session():
"""
Generator function offering dependency injection of SQLAlchemy Sessions.
Yields:
session: SQLAlchemy Session object
"""
session = Session(engine)
try:
yield session
finally:
session.close()