Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Is there a way to inject FastAPI Request object in the dependency chain? #19

Open
wadinj opened this issue Oct 5, 2024 · 2 comments
Open

Comments

@wadinj
Copy link

wadinj commented Oct 5, 2024

Hi,

We use middleware and request state to bind a SQLAlchemy session to a request. Is there a way to inject the Request object from FastAPI in magic-di dependency chain?

@RB387
Copy link
Collaborator

RB387 commented Oct 9, 2024

Hey 👋
magic-di dependencies are typically used in app scope. However, you can also combine them with fastapi’s request scope dependencies. Please correct me if I’m wrong, but I believe you can achieve it with something like this

from contextlib import asynccontextmanager
from fastapi import Request, Depends
from magic_di.fastapi import Provide
from magic_di import Connectable


class SQLAlchemy(Connectable):
   @asynccontextmanager
   async def start_session(self, request: Request):
       yield SQLAlchemySession(self, request)


async def get_sql_alchemy(request: Request, sql_alchemy: Provide[SQLAlchemy]) -> SQLAlchemySession:
    async with sql_alchemy.start_session(request) as session:
        yield session


@app.get('/test')
async def test_endpoint(sql_alchemy_session:  Annotated[SQLAlchemySession, Depends(get_sql_alchemy)]):
    ...

@wadinj
Copy link
Author

wadinj commented Oct 11, 2024

Thanks! I'll make a try.
There's no real consensus to bind the SQLAlchemy to the request lifecycle. Folks are sometimes using middleware, or Depends mechanism.

Do you have a best practices to bind 1 session per Request or per celery task with magic-di?

Awesome work with this DI injector ! Thank you

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants