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

Ascola/add middleware type alias #5898

Merged
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions CHANGES/5898.feature
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
Add a middleware type alias ``aiohttp.typedefs.Middleware``.
1 change: 1 addition & 0 deletions aiohttp/typedefs.py
Original file line number Diff line number Diff line change
Expand Up @@ -49,5 +49,6 @@
]

Handler = Callable[["Request"], Awaitable["StreamResponse"]]
Middleware = Callable[["Request", Handler], Awaitable["StreamResponse"]]

PathLike = Union[str, "os.PathLike[str]"]
13 changes: 5 additions & 8 deletions aiohttp/web_app.py
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@

from . import hdrs
from .log import web_logger
from .typedefs import Middleware
from .web_middlewares import _fix_request_current_app
from .web_request import Request
from .web_response import StreamResponse
Expand All @@ -46,20 +47,16 @@


if TYPE_CHECKING: # pragma: no cover
from .typedefs import Handler

_AppSignal = Signal[Callable[["Application"], Awaitable[None]]]
_RespPrepareSignal = Signal[Callable[[Request, StreamResponse], Awaitable[None]]]
_Middleware = Callable[[Request, Handler], Awaitable[StreamResponse]]
_Middlewares = FrozenList[_Middleware]
_MiddlewaresHandlers = Sequence[_Middleware]
_Middlewares = FrozenList[Middleware]
_MiddlewaresHandlers = Sequence[Middleware]
_Subapps = List["Application"]
else:
# No type checker mode, skip types
_AppSignal = Signal
_RespPrepareSignal = Signal
_Handler = Callable
_Middleware = Callable
_Middlewares = FrozenList
_MiddlewaresHandlers = Sequence
_Subapps = List
Expand Down Expand Up @@ -92,7 +89,7 @@ def __init__(
self,
*,
logger: logging.Logger = web_logger,
middlewares: Iterable[_Middleware] = (),
middlewares: Iterable[Middleware] = (),
handler_args: Optional[Mapping[str, Any]] = None,
client_max_size: int = 1024 ** 2,
debug: Any = ..., # mypy doesn't support ellipsis
Expand Down Expand Up @@ -325,7 +322,7 @@ async def cleanup(self) -> None:
# If an exception occurs in startup, ensure cleanup contexts are completed.
await self._cleanup_ctx._on_cleanup(self)

def _prepare_middleware(self) -> Iterator[_Middleware]:
def _prepare_middleware(self) -> Iterator[Middleware]:
yield from reversed(self._middlewares)
yield _fix_request_current_app(self)

Expand Down
11 changes: 4 additions & 7 deletions aiohttp/web_middlewares.py
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
import re
import warnings
from typing import TYPE_CHECKING, Awaitable, Callable, Tuple, Type, TypeVar
from typing import TYPE_CHECKING, Tuple, Type, TypeVar

from .typedefs import Handler
from .typedefs import Handler, Middleware
from .web_exceptions import HTTPMove, HTTPPermanentRedirect
from .web_request import Request
from .web_response import StreamResponse
Expand Down Expand Up @@ -42,16 +42,13 @@ def middleware(f: _Func) -> _Func:
return f


_Middleware = Callable[[Request, Handler], Awaitable[StreamResponse]]


def normalize_path_middleware(
*,
append_slash: bool = True,
remove_slash: bool = False,
merge_slashes: bool = True,
redirect_class: Type[HTTPMove] = HTTPPermanentRedirect,
) -> _Middleware:
) -> Middleware:
"""
Middleware factory which produces a middleware that normalizes
the path of a request. By normalizing it means:
Expand Down Expand Up @@ -118,7 +115,7 @@ async def impl(request: Request, handler: Handler) -> StreamResponse:
return impl


def _fix_request_current_app(app: "Application") -> _Middleware:
def _fix_request_current_app(app: "Application") -> Middleware:
async def impl(request: Request, handler: Handler) -> StreamResponse:
with request.match_info.set_current_app(app):
return await handler(request)
Expand Down