File tree Expand file tree Collapse file tree 1 file changed +28
-0
lines changed Expand file tree Collapse file tree 1 file changed +28
-0
lines changed Original file line number Diff line number Diff line change
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 ()
You can’t perform that action at this time.
0 commit comments