What would be the best way to inject per request objects. #686
Replies: 2 comments
-
|
We use a singleton dependency that serves as a factory for the needed object that needs request context - e.g.: def foo(bar: ForBar = Provide["bar"]):
baz = bar.create_baz(request.headers)
... |
Beta Was this translation helpful? Give feedback.
-
|
You can use ContextVar to do so. Have a look at https://github.com/romantolkachyov/pulya/blob/master/src/pulya/containers.py#L28 class RequestContainer(DeclarativeContainer):
ctx = Dependency(ContextVar)
request: Provider[Request] = Factory(ctx.provided.get.call())
headers = Factory(request.provided.headers)
body = Factory(_BodyWrapper, request.provided.get_content.call())This is my experiment on building FastAPI-looking web framework without FastAPI DI (and also using msgspec instead of pydantic; the two most annoying parts of FastAPI). I've end up with two separate containers (it's a little bit tricky to wire both at the same time). This is not a good idea to mix request into the main container because I will have no request in queue workers, CLI etc. So a handler in pulya may look like: @app.get("/wiring/{name}")
@inject
async def two_containers_wiring(
user: Annotated[str, Provide[Container.user]],
name: str,
headers: Annotated[Headers, Provide[RequestContainer.headers]],
) -> dict[str, Any]:
return {"test": "ok", "user": user, "name": name, "headers": list(headers)}Full app example: https://github.com/romantolkachyov/pulya/blob/master/examples/simple_example.py |
Beta Was this translation helpful? Give feedback.
Uh oh!
There was an error while loading. Please reload this page.
-
I need to get the auth headers from request object. What would be the best way to do this? Do I just use the flask request context in my service? Is there a similar pattern to spring per request beans? Or do i get header in the blueprint and then use the service factory there?
Beta Was this translation helpful? Give feedback.
All reactions