13 lines
826 B
Python
13 lines
826 B
Python
from typing import Generator
|
|
from sqlalchemy.orm import Session
|
|
from app.api.db.database import SessionLocal
|
|
def get_db() -> Generator[Session, None, None]:
|
|
db = SessionLocal()
|
|
try:
|
|
yield db
|
|
finally:
|
|
db.close()
|
|
```
|
|
This code defines a `get_db` function that returns a generator function. The generator function creates a new SQLAlchemy session using `SessionLocal` from `app.api.db.database` and yields the session. After the session is used, it is closed in the `finally` block.
|
|
The function signature `get_db() -> Generator[Session, None, None]` specifies that the function returns a generator that yields a `Session` object and does not receive or return any values.
|
|
This function is typically used as a dependency in FastAPI routes to provide a database session for querying and modifying data. |