diff --git a/.gitignore b/.gitignore index a63468e3a..2572a8256 100644 --- a/.gitignore +++ b/.gitignore @@ -14,4 +14,6 @@ __pycache__/ .mypy_cache/ .idea/ .vscode/ -.venv/ \ No newline at end of file +.venv/ + +uv.lock \ No newline at end of file diff --git a/docs/integrations/litestar.rst b/docs/integrations/litestar.rst index 18994625d..1bdd1b576 100644 --- a/docs/integrations/litestar.rst +++ b/docs/integrations/litestar.rst @@ -22,6 +22,7 @@ How to use LitestarProvider, inject, setup_dishka, + DishkaRouter, ) from dishka import make_async_container, Provider, provide, Scope @@ -46,6 +47,19 @@ How to use ) -> Response: ... +3a. *(optional)* Set route class to each of your fastapi routers to enable automatic injection (it works only for HTTP, not for websockets) + +.. code-block:: python + + @router.get('/') + async def endpoint( + request: str, gateway: FromDishka[Gateway], + ) -> Response: + ... + + r = DishkaRouter('', route_handlers=[endpoint]) + app = Litestar(route_handlers=[r]) + 4. *(optional)* Use ``LitestarProvider()`` when creating container if you are going to use ``litestar.Request`` in providers. diff --git a/src/dishka/integrations/litestar.py b/src/dishka/integrations/litestar.py index 0045f167d..0c7505704 100644 --- a/src/dishka/integrations/litestar.py +++ b/src/dishka/integrations/litestar.py @@ -10,7 +10,7 @@ from inspect import Parameter from typing import ParamSpec, TypeVar, get_type_hints -from litestar import Litestar, Request, WebSocket +from litestar import Litestar, Request, WebSocket, Router from litestar.enums import ScopeType from litestar.types import ASGIApp, Receive, Scope, Send @@ -93,3 +93,9 @@ def setup_dishka(container: AsyncContainer, app: Litestar) -> None: app.asgi_handler, ) app.state.dishka_container = container + + +class DishkaRouter(Router): + def register(self, value): + value._fn = inject(value._fn) + return super().register(value) diff --git a/tests/integrations/litestar/test_litestar.py b/tests/integrations/litestar/test_litestar.py index a1fcb0b22..c323a5aef 100644 --- a/tests/integrations/litestar/test_litestar.py +++ b/tests/integrations/litestar/test_litestar.py @@ -13,6 +13,7 @@ FromDishka, inject, setup_dishka, + DishkaRouter ) from ..common import ( APP_DEP_VALUE, @@ -29,8 +30,11 @@ async def dishka_app( provider, request_class: type[Request] = Request, ) -> TestClient: - app = litestar.Litestar(request_class=request_class) - app.register(get("/")(inject(view))) + dishka_router = DishkaRouter('', route_handlers=[]) + dishka_router.register(get("/")(view)) + + app = litestar.Litestar(route_handlers=[dishka_router], request_class=request_class) + # app.register(get("/")(inject(view))) app.register(websocket_listener("/ws")(websocket_handler)) container = make_async_container(provider) setup_dishka(container, app)