4/app/api/core/dependencies/dependencies.py
2025-03-20 09:54:31 +01:00

46 lines
1.8 KiB
Python

Here's the `dependencies.py` file for the specified location `app/api/core/dependencies/`:
```python
from typing import Generator
from sqlalchemy.orm import Session
from app.api.db.database import SessionLocal
def get_db() -> Generator[Session, None, None]:
"""
Dependency function that provides a SQLAlchemy session.
Yields:
Session: A SQLAlchemy session instance.
"""
db = SessionLocal()
try:
yield db
finally:
db.close()
```
This file defines a `get_db` function that serves as a dependency for FastAPI routes that require a database session. The function uses the `SessionLocal` object from `app.api.db.database` to create a new SQLAlchemy session, which is then yielded to the requesting route.
The `get_db` function is a generator function that yields the session instance and ensures it is properly closed after the requesting route has finished executing.
To use this dependency in a FastAPI route, you can include it as a function parameter, and FastAPI will automatically resolve the dependency by calling the `get_db` function and providing the yielded session instance. For example:
```python
from fastapi import APIRouter, Depends
from sqlalchemy.orm import Session
from app.api.core.dependencies import get_db
router = APIRouter()
@router.get("/items")
def get_items(db: Session = Depends(get_db)):
# Use the provided db session to interact with the database
...
```
In this example, the `get_items` route receives a `Session` instance as the `db` parameter, which is automatically provided by FastAPI by calling the `get_db` dependency function.
Note that you'll need to configure the `SessionLocal` object in `app.api.db.database` to connect to your SQLite database using the appropriate connection string and engine configuration.