from collections.abc import Awaitable, Callable
from functools import wraps
from typing import Concatenate, ParamSpec, TypeVar
from aiohttp import web
Params = ParamSpec("Params")
Request = TypeVar("Request", bound=web.Request)
Response = TypeVar("Response", bound=web.StreamResponse)
Handler = Callable[Concatenate[Request, Params], Awaitable[Response]]
# TODO: заменить типизацию во всех wrapper c `web.Request` на `Request`
# после закрытия дефекта: https://youtrack.jetbrains.com/issue/PY-66446
def some_decorator(handler: Handler) -> Handler:
"""Какой-то декоратор."""
@wraps(handler)
async def wrapper(
request: web.Request,
*args: Params.args,
**kwargs: Params.kwargs,
) -> Response:
# do something before
result = await handler(request, *args, **kwargs)
# do something after
return result
return wrapper
@some_decorator
async def echo_handler(request: Request) -> Response:
echo = await request.text()
return web.Response(text=echo)
Created
February 8, 2024 11:33
-
-
Save Olegt0rr/ad152edc44916573bd07c8cf9850d4c0 to your computer and use it in GitHub Desktop.
aiohttp handler decorator type hints
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment