-
Notifications
You must be signed in to change notification settings - Fork 114
feat(litestar): add support for guards with ASGIConnection parameter #700
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
Open
arynyklas
wants to merge
7
commits into
reagento:develop
Choose a base branch
from
arynyklas:develop
base: develop
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
+137
−11
Open
Changes from 6 commits
Commits
Show all changes
7 commits
Select commit
Hold shift + click to select a range
d58ec95
feat(litestar): add ASGIConnection and guard dependency support
arynyklas 6245b47
feat(litestar): add inject_asgi for guards (#699)
arynyklas c7fb3ff
docs(litestar): add guard usage with inject_asgi
arynyklas a95868d
feat(litestar): add documentation for @inject_asgi decorator in Guard…
arynyklas a633fc3
test(litestar): add tests for inject_asgi guard decorator
arynyklas 545baa2
test(litestar): fix Guard import and simplify guard tests
arynyklas 06ed977
style: fix typing in litestar integration
arynyklas File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -3,14 +3,15 @@ | |
| "FromDishka", | ||
| "LitestarProvider", | ||
| "inject", | ||
| "inject_asgi", | ||
| "inject_websocket", | ||
| "setup_dishka", | ||
| ] | ||
|
|
||
| from collections.abc import Callable | ||
| from functools import wraps | ||
| from inspect import Parameter | ||
| from typing import ParamSpec, TypeVar, get_type_hints | ||
| from inspect import Parameter, Signature, signature | ||
| from typing import Any, ParamSpec, TypeVar, get_type_hints, overload | ||
|
|
||
| from litestar import Controller, Litestar, Request, Router, WebSocket | ||
| from litestar.enums import ScopeType | ||
|
|
@@ -19,6 +20,7 @@ | |
| HTTPRouteHandler, | ||
| WebsocketListener, | ||
| ) | ||
| from litestar.connection import ASGIConnection | ||
| from litestar.handlers.websocket_handlers import WebsocketListenerRouteHandler | ||
| from litestar.handlers.websocket_handlers._utils import ListenerHandler | ||
| from litestar.routes import BaseRoute | ||
|
|
@@ -34,22 +36,38 @@ | |
| from dishka import Scope as DIScope | ||
| from dishka.integrations.base import wrap_injection | ||
|
|
||
| GuardDependencyT = TypeVar("GuardDependencyT") | ||
| P = ParamSpec("P") | ||
| T = TypeVar("T") | ||
|
|
||
|
|
||
| @overload | ||
| def inject( | ||
| func: Callable[[ASGIConnection, BaseRouteHandler, GuardDependencyT], T], | ||
| /, | ||
| ) -> Callable[[ASGIConnection, BaseRouteHandler], T]: ... | ||
|
|
||
|
|
||
| @overload | ||
| def inject(func: Callable[P, T], /) -> Callable[P, T]: ... | ||
|
|
||
|
|
||
| def inject(func: Callable[P, T]) -> Callable[P, T]: | ||
| return _inject_wrapper(func, "request", Request) | ||
|
|
||
|
|
||
| def inject_asgi(func: Callable[P, T]) -> Callable[P, T]: | ||
| return _inject_wrapper(func, "connection", ASGIConnection) | ||
|
|
||
|
|
||
| def inject_websocket(func: Callable[P, T]) -> Callable[P, T]: | ||
| return _inject_wrapper(func, "socket", WebSocket) | ||
|
|
||
|
|
||
| def _inject_wrapper( | ||
| func: Callable[P, T], | ||
| param_name: str, | ||
| param_annotation: type[Request | WebSocket], | ||
| func: Callable[P, T], | ||
| param_name: str, | ||
| param_annotation: type[Request | WebSocket | ASGIConnection], | ||
| ) -> Callable[P, T]: | ||
| hints = get_type_hints(func) | ||
|
|
||
|
|
@@ -67,11 +85,16 @@ def _inject_wrapper( | |
| kind=Parameter.KEYWORD_ONLY, | ||
| )] | ||
|
|
||
| if param_name == "connection": | ||
|
Member
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. I do not see why user won't put param called connection at any other position in normal handler |
||
| container_getter = lambda args, _: args[0].state.dishka_container | ||
| else: | ||
| container_getter = lambda _, kwargs: kwargs[param_name].state.dishka_container | ||
|
|
||
| return wrap_injection( | ||
| func=func, | ||
| is_async=True, | ||
| additional_params=additional_params, | ||
| container_getter=lambda _, r: r[param_name].state.dishka_container, | ||
| container_getter=container_getter, | ||
| ) | ||
|
|
||
|
|
||
|
|
||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,81 @@ | ||
| from collections.abc import AsyncGenerator | ||
| from contextlib import asynccontextmanager | ||
| from unittest.mock import Mock | ||
|
|
||
| import pytest | ||
| from asgi_lifespan import LifespanManager | ||
| from litestar import Litestar, get | ||
| from litestar.connection import ASGIConnection | ||
| from litestar.handlers import BaseRouteHandler | ||
| from litestar.types import Guard | ||
| from litestar.testing import TestClient | ||
|
|
||
| from dishka import make_async_container | ||
| from dishka.integrations.litestar import ( | ||
| DishkaRouter, | ||
| FromDishka, | ||
| inject_asgi, | ||
| setup_dishka, | ||
| ) | ||
| from ..common import ( | ||
| APP_DEP_VALUE, | ||
| AppDep, | ||
| AppProvider, | ||
| ) | ||
|
|
||
|
|
||
| @asynccontextmanager | ||
| async def dishka_app(guard: Guard, provider: AppProvider) -> AsyncGenerator[TestClient, None]: | ||
| @get("/", guards=[guard]) | ||
| async def endpoint() -> dict: | ||
| return {"status": "ok"} | ||
|
|
||
| app = Litestar([endpoint], debug=True) | ||
| container = make_async_container(provider) | ||
| setup_dishka(container, app) | ||
| async with LifespanManager(app): | ||
| yield TestClient(app) | ||
| await container.close() | ||
|
|
||
|
|
||
| @asynccontextmanager | ||
| async def dishka_auto_app(guard: Guard, provider: AppProvider) -> AsyncGenerator[TestClient, None]: | ||
| @get("/") | ||
| async def endpoint() -> dict: | ||
| return {"status": "ok"} | ||
|
|
||
| router = DishkaRouter("", route_handlers=[endpoint], guards=[guard]) | ||
| app = Litestar([router], debug=True) | ||
| container = make_async_container(provider) | ||
| setup_dishka(container, app) | ||
| async with LifespanManager(app): | ||
| yield TestClient(app) | ||
| await container.close() | ||
|
|
||
|
|
||
| @inject_asgi | ||
| async def guard_with_app( | ||
| connection: ASGIConnection, | ||
| _: BaseRouteHandler, | ||
| a: FromDishka[AppDep], | ||
| mock: FromDishka[Mock], | ||
| ) -> None: | ||
| mock(a) | ||
|
|
||
|
|
||
| @pytest.mark.asyncio | ||
| @pytest.mark.parametrize( | ||
| ("app_factory", "guard"), | ||
| [ | ||
| (dishka_app, guard_with_app), | ||
| ], | ||
| ) | ||
| async def test_guard_injects_app_dependency( | ||
| app_factory, | ||
| guard, | ||
| app_provider: AppProvider, | ||
| ): | ||
| async with app_factory(guard, app_provider) as client: | ||
| response = client.get("/") | ||
| assert response.status_code == 200 | ||
| app_provider.mock.assert_called_with(APP_DEP_VALUE) |
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Can it be used somewhere else?
inject_asgisounds like something more generic than guards only