24 lines
1.2 KiB
Python
24 lines
1.2 KiB
Python
Here's the `dependencies.py` file for the specified path `app/api/core/dependencies/`:
|
|
```python
|
|
from contextlib import contextmanager
|
|
from sqlalchemy.orm import Session
|
|
from app.api.db.database import SessionLocal
|
|
@contextmanager
|
|
def get_db() -> Session:
|
|
db = SessionLocal()
|
|
try:
|
|
yield db
|
|
finally:
|
|
db.close()
|
|
```
|
|
This file defines a context manager function `get_db` that creates a new SQLAlchemy `Session` using the `SessionLocal` imported from `app.api.db.database`. The session is yielded within the context manager, and it is automatically closed when the context manager exits, ensuring proper resource management.
|
|
To use this function in your application, you can import it and use it as a dependency in your API routes or services that require database access. For example:
|
|
```python
|
|
from fastapi import Depends
|
|
from app.api.core.dependencies import get_db
|
|
# In your API route or service
|
|
def my_function(db: Session = Depends(get_db)):
|
|
# Use the database session 'db' here
|
|
...
|
|
```
|
|
By using the `Depends` function from FastAPI, the `get_db` function will be called for each request, and the resulting database session will be injected as a dependency into your function. |