Skip to content
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
10 changes: 2 additions & 8 deletions aiohttp/abc.py
Original file line number Diff line number Diff line change
Expand Up @@ -147,16 +147,10 @@ async def close(self) -> None:
"""Release resolver"""


if TYPE_CHECKING:
IterableBase = Iterable[Morsel[str]]
else:
IterableBase = Iterable


ClearCookiePredicate = Callable[["Morsel[str]"], bool]
ClearCookiePredicate = Callable[[Morsel[str]], bool]


class AbstractCookieJar(Sized, IterableBase):
class AbstractCookieJar(Sized, Iterable[Morsel[str]]):
"""Abstract Cookie Jar."""

@property
Expand Down
4 changes: 2 additions & 2 deletions aiohttp/client.py
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@
from typing import TYPE_CHECKING, Any, Final, Generic, TypedDict, TypeVar, final

from multidict import CIMultiDict, MultiDict, MultiDictProxy, istr
from yarl import URL
from yarl import URL, Query

from . import hdrs, http, payload
from ._websocket.reader import WebSocketDataQueue
Expand Down Expand Up @@ -96,7 +96,7 @@
from .http import WS_KEY, HttpVersion, WebSocketReader, WebSocketWriter
from .http_websocket import WSHandshakeError, ws_ext_gen, ws_ext_parse
from .tracing import Trace, TraceConfig
from .typedefs import JSONEncoder, LooseCookies, LooseHeaders, Query, StrOrURL
from .typedefs import JSONEncoder, LooseCookies, LooseHeaders, StrOrURL

__all__ = (
# client_exceptions
Expand Down
11 changes: 3 additions & 8 deletions aiohttp/client_exceptions.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,17 +7,12 @@

from .typedefs import StrOrURL

if TYPE_CHECKING:
try:
import ssl

SSLContext = ssl.SSLContext
else:
try:
import ssl

SSLContext = ssl.SSLContext
except ImportError: # pragma: no cover
ssl = SSLContext = None # type: ignore[assignment]
except ImportError: # pragma: no cover
ssl = SSLContext = None # type: ignore[assignment]

if TYPE_CHECKING:
from .client_reqrep import ClientResponse, ConnectionKey, Fingerprint, RequestInfo
Expand Down
16 changes: 6 additions & 10 deletions aiohttp/client_reqrep.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@
from typing import TYPE_CHECKING, Any, NamedTuple, TypedDict

from multidict import CIMultiDict, CIMultiDictProxy, MultiDict, MultiDictProxy
from yarl import URL
from yarl import URL, Query

from . import hdrs, multipart, payload
from ._cookie_helpers import (
Expand Down Expand Up @@ -57,18 +57,14 @@
StreamWriter,
)
from .streams import StreamReader
from .typedefs import DEFAULT_JSON_DECODER, JSONDecoder, Query, RawHeaders
from .typedefs import DEFAULT_JSON_DECODER, JSONDecoder, RawHeaders

if TYPE_CHECKING:
try:
import ssl
from ssl import SSLContext
else:
try:
import ssl
from ssl import SSLContext
except ImportError: # pragma: no cover
ssl = None # type: ignore[assignment]
SSLContext = object # type: ignore[misc,assignment]
except ImportError: # pragma: no cover
ssl = None # type: ignore[assignment]
SSLContext = object # type: ignore[misc,assignment]


__all__ = ("ClientRequest", "ClientResponse", "RequestInfo", "Fingerprint")
Expand Down
13 changes: 4 additions & 9 deletions aiohttp/connector.py
Original file line number Diff line number Diff line change
Expand Up @@ -56,18 +56,13 @@
else:
Buffer = "bytes | bytearray | memoryview[int] | memoryview[bytes]"

if TYPE_CHECKING:
try:
import ssl

SSLContext = ssl.SSLContext
else:
try:
import ssl

SSLContext = ssl.SSLContext
except ImportError: # pragma: no cover
ssl = None # type: ignore[assignment]
SSLContext = object # type: ignore[misc,assignment]
except ImportError: # pragma: no cover
ssl = None # type: ignore[assignment]
SSLContext = object # type: ignore[misc,assignment]

EMPTY_SCHEMA_SET = frozenset({""})
HTTP_SCHEMA_SET = frozenset({"http", "https"})
Expand Down
8 changes: 5 additions & 3 deletions aiohttp/http_exceptions.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@

from textwrap import indent

from .typedefs import _CIMultiDict
from multidict import CIMultiDict

__all__ = ("HttpProcessingError",)

Expand All @@ -26,7 +26,7 @@ def __init__(
*,
code: int | None = None,
message: str = "",
headers: _CIMultiDict | None = None,
headers: CIMultiDict[str] | None = None,
) -> None:
if code is not None:
self.code = code
Expand All @@ -45,7 +45,9 @@ class BadHttpMessage(HttpProcessingError):
code = 400
message = "Bad Request"

def __init__(self, message: str, *, headers: _CIMultiDict | None = None) -> None:
def __init__(
self, message: str, *, headers: CIMultiDict[str] | None = None
) -> None:
super().__init__(message=message, headers=headers)
self.args = (message,)

Expand Down
30 changes: 9 additions & 21 deletions aiohttp/payload.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,9 +7,9 @@
import sys
import warnings
from abc import ABC, abstractmethod
from collections.abc import Iterable
from collections.abc import AsyncIterable, AsyncIterator, Iterable
from itertools import chain
from typing import IO, TYPE_CHECKING, Any, Final, TextIO
from typing import IO, Any, Final, TextIO

from multidict import CIMultiDict

Expand All @@ -23,7 +23,7 @@
sentinel,
)
from .streams import StreamReader
from .typedefs import JSONEncoder, _CIMultiDict
from .typedefs import JSONEncoder

__all__ = (
"PAYLOAD_REGISTRY",
Expand Down Expand Up @@ -145,7 +145,7 @@ def __init__(
self,
value: Any,
headers: (
_CIMultiDict | dict[str, str] | Iterable[tuple[str, str]] | None
CIMultiDict[str] | dict[str, str] | Iterable[tuple[str, str]] | None
) = None,
content_type: None | str | _SENTINEL = sentinel,
filename: str | None = None,
Expand All @@ -154,7 +154,7 @@ def __init__(
) -> None:
self._encoding = encoding
self._filename = filename
self._headers: _CIMultiDict = CIMultiDict()
self._headers = CIMultiDict[str]()
self._value = value
if content_type is not sentinel and content_type is not None:
assert isinstance(content_type, str)
Expand Down Expand Up @@ -189,7 +189,7 @@ def filename(self) -> str | None:
return self._filename

@property
def headers(self) -> _CIMultiDict:
def headers(self) -> CIMultiDict[str]:
"""Custom item headers"""
return self._headers

Expand Down Expand Up @@ -939,26 +939,14 @@ def __init__(
)


if TYPE_CHECKING:
from collections.abc import AsyncIterable, AsyncIterator

_AsyncIterator = AsyncIterator[bytes]
_AsyncIterable = AsyncIterable[bytes]
else:
from collections.abc import AsyncIterable, AsyncIterator

_AsyncIterator = AsyncIterator
_AsyncIterable = AsyncIterable


class AsyncIterablePayload(Payload):
_iter: _AsyncIterator | None = None
_value: _AsyncIterable
_iter: AsyncIterator[bytes] | None = None
_value: AsyncIterable[bytes]
_cached_chunks: list[bytes] | None = None
# _consumed stays False to allow reuse with cached content
_autoclose = True # Iterator doesn't need explicit closing

def __init__(self, value: _AsyncIterable, *args: Any, **kwargs: Any) -> None:
def __init__(self, value: AsyncIterable[bytes], *args: Any, **kwargs: Any) -> None:
if not isinstance(value, AsyncIterable):
raise TypeError(
"value argument must support "
Expand Down
54 changes: 18 additions & 36 deletions aiohttp/typedefs.py
Original file line number Diff line number Diff line change
@@ -1,52 +1,34 @@
import json
import os
from collections.abc import Awaitable, Callable, Iterable, Mapping
from typing import TYPE_CHECKING, Any, Protocol, Union
from http.cookies import BaseCookie, Morsel
from typing import TYPE_CHECKING, Any, Protocol

from multidict import CIMultiDict, CIMultiDictProxy, MultiDict, MultiDictProxy, istr
from yarl import URL, Query as _Query

Query = _Query
from multidict import CIMultiDict, CIMultiDictProxy, istr
from yarl import URL

DEFAULT_JSON_ENCODER = json.dumps
DEFAULT_JSON_DECODER = json.loads

if TYPE_CHECKING:
_CIMultiDict = CIMultiDict[str]
_CIMultiDictProxy = CIMultiDictProxy[str]
_MultiDict = MultiDict[str]
_MultiDictProxy = MultiDictProxy[str]
from http.cookies import BaseCookie, Morsel

from .web import Request, StreamResponse
else:
_CIMultiDict = CIMultiDict
_CIMultiDictProxy = CIMultiDictProxy
_MultiDict = MultiDict
_MultiDictProxy = MultiDictProxy

Byteish = Union[bytes, bytearray, memoryview]
Byteish = bytes | bytearray | memoryview
JSONEncoder = Callable[[Any], str]
JSONDecoder = Callable[[str], Any]
LooseHeaders = Union[
Mapping[str, str],
Mapping[istr, str],
_CIMultiDict,
_CIMultiDictProxy,
Iterable[tuple[str | istr, str]],
]
LooseHeaders = (
Mapping[str, str]
| Mapping[istr, str]
| CIMultiDict[str]
| CIMultiDictProxy[str]
| Iterable[tuple[str | istr, str]]
)
RawHeaders = tuple[tuple[bytes, bytes], ...]
StrOrURL = Union[str, URL]

LooseCookiesMappings = Mapping[str, Union[str, "BaseCookie[str]", "Morsel[Any]"]]
LooseCookiesIterables = Iterable[
tuple[str, Union[str, "BaseCookie[str]", "Morsel[Any]"]]
]
LooseCookies = Union[
LooseCookiesMappings,
LooseCookiesIterables,
"BaseCookie[str]",
]
StrOrURL = str | URL

LooseCookiesMappings = Mapping[str, str | BaseCookie[str] | Morsel[Any]]
LooseCookiesIterables = Iterable[tuple[str, str | BaseCookie[str] | Morsel[Any]]]
LooseCookies = LooseCookiesMappings | LooseCookiesIterables | BaseCookie[str]

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

Expand All @@ -57,4 +39,4 @@ def __call__(
) -> Awaitable["StreamResponse"]: ...


PathLike = Union[str, "os.PathLike[str]"]
PathLike = str | os.PathLike[str]
11 changes: 4 additions & 7 deletions aiohttp/web.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@
from collections.abc import Awaitable, Callable, Iterable, Iterable as TypingIterable
from contextlib import suppress
from importlib import import_module
from typing import TYPE_CHECKING, Any, cast
from typing import Any, cast

from .abc import AbstractAccessLogger
from .helpers import AppKey
Expand Down Expand Up @@ -256,13 +256,10 @@
)


if TYPE_CHECKING:
try:
from ssl import SSLContext
else:
try:
from ssl import SSLContext
except ImportError: # pragma: no cover
SSLContext = object # type: ignore[misc,assignment]
except ImportError: # pragma: no cover
SSLContext = object # type: ignore[misc,assignment]

# Only display warning when using -Wdefault, -We, -X dev or similar.
warnings.filterwarnings("ignore", category=NotAppKeyWarning, append=True)
Expand Down
27 changes: 7 additions & 20 deletions aiohttp/web_app.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@
Sequence,
)
from functools import lru_cache, partial, update_wrapper
from typing import TYPE_CHECKING, Any, TypeVar, cast, final, overload
from typing import Any, TypeVar, cast, final, overload

from aiosignal import Signal
from frozenlist import FrozenList
Expand All @@ -39,21 +39,11 @@

__all__ = ("Application", "CleanupError")


if TYPE_CHECKING:
_AppSignal = Signal["Application"]
_RespPrepareSignal = Signal[Request, StreamResponse]
_Middlewares = FrozenList[Middleware]
_MiddlewaresHandlers = Sequence[Middleware]
_Subapps = list["Application"]
else:
# No type checker mode, skip types
_AppSignal = Signal
_RespPrepareSignal = Signal
_Handler = Callable
_Middlewares = FrozenList
_MiddlewaresHandlers = Sequence
_Subapps = list
_AppSignal = Signal["Application"]
_RespPrepareSignal = Signal[Request, StreamResponse]
_Middlewares = FrozenList[Middleware]
_MiddlewaresHandlers = Sequence[Middleware]
_Subapps = list["Application"]

_T = TypeVar("_T")
_U = TypeVar("_U")
Expand Down Expand Up @@ -415,10 +405,7 @@ def exceptions(self) -> list[BaseException]:
return cast(list[BaseException], self.args[1])


if TYPE_CHECKING:
_CleanupContextBase = FrozenList[Callable[[Application], AsyncIterator[None]]]
else:
_CleanupContextBase = FrozenList
_CleanupContextBase = FrozenList[Callable[[Application], AsyncIterator[None]]]


class CleanupContext(_CleanupContextBase):
Expand Down
7 changes: 1 addition & 6 deletions aiohttp/web_response.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
import asyncio
import collections.abc
import datetime
import enum
import json
Expand Down Expand Up @@ -43,10 +42,6 @@
if TYPE_CHECKING:
from .web_request import BaseRequest

BaseClass = MutableMapping[str, Any]
else:
BaseClass = collections.abc.MutableMapping


# TODO(py311): Convert to StrEnum for wider use
class ContentCoding(enum.Enum):
Expand All @@ -66,7 +61,7 @@ class ContentCoding(enum.Enum):
############################################################


class StreamResponse(BaseClass, HeadersMixin, CookieMixin):
class StreamResponse(MutableMapping[str, Any], HeadersMixin, CookieMixin):

_body: None | bytes | bytearray | Payload
_length_check = True
Expand Down
Loading
Loading