Voice et bot modif
This commit is contained in:
parent
189d56026b
commit
7333a22bcd
10774 changed files with 634644 additions and 933308 deletions
|
|
@ -6,30 +6,23 @@ import json
|
|||
import math
|
||||
import time
|
||||
import warnings
|
||||
from collections.abc import Iterator, MutableMapping
|
||||
from concurrent.futures import Executor
|
||||
from http import HTTPStatus
|
||||
from http.cookies import SimpleCookie
|
||||
from typing import (
|
||||
TYPE_CHECKING,
|
||||
Any,
|
||||
Dict,
|
||||
Iterator,
|
||||
MutableMapping,
|
||||
Optional,
|
||||
Union,
|
||||
cast,
|
||||
)
|
||||
from typing import TYPE_CHECKING, Any, Optional, TypeVar, cast, overload
|
||||
|
||||
from multidict import CIMultiDict, istr
|
||||
|
||||
from . import hdrs, payload
|
||||
from .abc import AbstractStreamWriter
|
||||
from .compression_utils import ZLibCompressor
|
||||
from .compression_utils import MAX_SYNC_CHUNK_SIZE, ZLibCompressor
|
||||
from .helpers import (
|
||||
ETAG_ANY,
|
||||
QUOTED_ETAG_RE,
|
||||
ETag,
|
||||
HeadersMixin,
|
||||
ResponseKey,
|
||||
must_be_empty_body,
|
||||
parse_http_date,
|
||||
rfc822_formatted_time,
|
||||
|
|
@ -39,12 +32,17 @@ from .helpers import (
|
|||
)
|
||||
from .http import SERVER_SOFTWARE, HttpVersion10, HttpVersion11
|
||||
from .payload import Payload
|
||||
from .typedefs import JSONEncoder, LooseHeaders
|
||||
from .typedefs import JSONBytesEncoder, JSONEncoder, LooseHeaders
|
||||
|
||||
REASON_PHRASES = {http_status.value: http_status.phrase for http_status in HTTPStatus}
|
||||
LARGE_BODY_SIZE = 1024**2
|
||||
|
||||
__all__ = ("ContentCoding", "StreamResponse", "Response", "json_response")
|
||||
__all__ = (
|
||||
"ContentCoding",
|
||||
"StreamResponse",
|
||||
"Response",
|
||||
"json_response",
|
||||
"json_bytes_response",
|
||||
)
|
||||
|
||||
|
||||
if TYPE_CHECKING:
|
||||
|
|
@ -55,6 +53,9 @@ else:
|
|||
BaseClass = collections.abc.MutableMapping
|
||||
|
||||
|
||||
_T = TypeVar("_T")
|
||||
|
||||
|
||||
# TODO(py311): Convert to StrEnum for wider use
|
||||
class ContentCoding(enum.Enum):
|
||||
# The content codings that we have support for.
|
||||
|
|
@ -73,31 +74,32 @@ CONTENT_CODINGS = {coding.value: coding for coding in ContentCoding}
|
|||
############################################################
|
||||
|
||||
|
||||
class StreamResponse(BaseClass, HeadersMixin):
|
||||
class StreamResponse(MutableMapping[str | ResponseKey[Any], Any], HeadersMixin):
|
||||
|
||||
_body: Union[None, bytes, bytearray, Payload]
|
||||
_body: None | bytes | bytearray | Payload
|
||||
_length_check = True
|
||||
_body = None
|
||||
_keep_alive: Optional[bool] = None
|
||||
_keep_alive: bool | None = None
|
||||
_chunked: bool = False
|
||||
_compression: bool = False
|
||||
_compression_strategy: Optional[int] = None
|
||||
_compression_force: Optional[ContentCoding] = None
|
||||
_compression_strategy: int | None = None
|
||||
_compression_force: ContentCoding | None = None
|
||||
_req: Optional["BaseRequest"] = None
|
||||
_payload_writer: Optional[AbstractStreamWriter] = None
|
||||
_payload_writer: AbstractStreamWriter | None = None
|
||||
_eof_sent: bool = False
|
||||
_must_be_empty_body: Optional[bool] = None
|
||||
_must_be_empty_body: bool | None = None
|
||||
_body_length = 0
|
||||
_cookies: Optional[SimpleCookie] = None
|
||||
_cookies: SimpleCookie | None = None
|
||||
_send_headers_immediately = True
|
||||
_seen_str_keys: set[str] = set()
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
*,
|
||||
status: int = 200,
|
||||
reason: Optional[str] = None,
|
||||
headers: Optional[LooseHeaders] = None,
|
||||
_real_headers: Optional[CIMultiDict[str]] = None,
|
||||
reason: str | None = None,
|
||||
headers: LooseHeaders | None = None,
|
||||
_real_headers: CIMultiDict[str] | None = None,
|
||||
) -> None:
|
||||
"""Initialize a new stream response object.
|
||||
|
||||
|
|
@ -106,7 +108,7 @@ class StreamResponse(BaseClass, HeadersMixin):
|
|||
the headers when creating a new response object. It is not intended
|
||||
to be used by external code.
|
||||
"""
|
||||
self._state: Dict[str, Any] = {}
|
||||
self._state: dict[str | ResponseKey[Any], Any] = {}
|
||||
|
||||
if _real_headers is not None:
|
||||
self._headers = _real_headers
|
||||
|
|
@ -122,7 +124,7 @@ class StreamResponse(BaseClass, HeadersMixin):
|
|||
return self._eof_sent or self._payload_writer is not None
|
||||
|
||||
@property
|
||||
def task(self) -> "Optional[asyncio.Task[None]]":
|
||||
def task(self) -> "asyncio.Task[None] | None":
|
||||
if self._req:
|
||||
return self._req.task
|
||||
else:
|
||||
|
|
@ -147,23 +149,23 @@ class StreamResponse(BaseClass, HeadersMixin):
|
|||
def set_status(
|
||||
self,
|
||||
status: int,
|
||||
reason: Optional[str] = None,
|
||||
reason: str | None = None,
|
||||
) -> None:
|
||||
assert (
|
||||
not self.prepared
|
||||
), "Cannot change the response status code after the headers have been sent"
|
||||
self._set_status(status, reason)
|
||||
|
||||
def _set_status(self, status: int, reason: Optional[str]) -> None:
|
||||
def _set_status(self, status: int, reason: str | None) -> None:
|
||||
self._status = int(status)
|
||||
if reason is None:
|
||||
reason = REASON_PHRASES.get(self._status, "")
|
||||
elif "\n" in reason:
|
||||
raise ValueError("Reason cannot contain \\n")
|
||||
elif "\r" in reason or "\n" in reason:
|
||||
raise ValueError("Reason cannot contain \\r or \\n")
|
||||
self._reason = reason
|
||||
|
||||
@property
|
||||
def keep_alive(self) -> Optional[bool]:
|
||||
def keep_alive(self) -> bool | None:
|
||||
return self._keep_alive
|
||||
|
||||
def force_close(self) -> None:
|
||||
|
|
@ -179,7 +181,7 @@ class StreamResponse(BaseClass, HeadersMixin):
|
|||
assert self._payload_writer
|
||||
return self._payload_writer.buffer_size
|
||||
|
||||
def enable_chunked_encoding(self, chunk_size: Optional[int] = None) -> None:
|
||||
def enable_chunked_encoding(self, chunk_size: int | None = None) -> None:
|
||||
"""Enables automatic chunked transfer encoding."""
|
||||
if hdrs.CONTENT_LENGTH in self._headers:
|
||||
raise RuntimeError(
|
||||
|
|
@ -191,8 +193,8 @@ class StreamResponse(BaseClass, HeadersMixin):
|
|||
|
||||
def enable_compression(
|
||||
self,
|
||||
force: Optional[Union[bool, ContentCoding]] = None,
|
||||
strategy: Optional[int] = None,
|
||||
force: bool | ContentCoding | None = None,
|
||||
strategy: int | None = None,
|
||||
) -> None:
|
||||
"""Enables response compression encoding."""
|
||||
# Backwards compatibility for when force was a bool <0.17.
|
||||
|
|
@ -225,15 +227,15 @@ class StreamResponse(BaseClass, HeadersMixin):
|
|||
name: str,
|
||||
value: str,
|
||||
*,
|
||||
expires: Optional[str] = None,
|
||||
domain: Optional[str] = None,
|
||||
max_age: Optional[Union[int, str]] = None,
|
||||
expires: str | None = None,
|
||||
domain: str | None = None,
|
||||
max_age: int | str | None = None,
|
||||
path: str = "/",
|
||||
secure: Optional[bool] = None,
|
||||
httponly: Optional[bool] = None,
|
||||
version: Optional[str] = None,
|
||||
samesite: Optional[str] = None,
|
||||
partitioned: Optional[bool] = None,
|
||||
secure: bool | None = None,
|
||||
httponly: bool | None = None,
|
||||
version: str | None = None,
|
||||
samesite: str | None = None,
|
||||
partitioned: bool | None = None,
|
||||
) -> None:
|
||||
"""Set or update response cookie.
|
||||
|
||||
|
|
@ -277,11 +279,11 @@ class StreamResponse(BaseClass, HeadersMixin):
|
|||
self,
|
||||
name: str,
|
||||
*,
|
||||
domain: Optional[str] = None,
|
||||
domain: str | None = None,
|
||||
path: str = "/",
|
||||
secure: Optional[bool] = None,
|
||||
httponly: Optional[bool] = None,
|
||||
samesite: Optional[str] = None,
|
||||
secure: bool | None = None,
|
||||
httponly: bool | None = None,
|
||||
samesite: str | None = None,
|
||||
) -> None:
|
||||
"""Delete cookie.
|
||||
|
||||
|
|
@ -303,12 +305,12 @@ class StreamResponse(BaseClass, HeadersMixin):
|
|||
)
|
||||
|
||||
@property
|
||||
def content_length(self) -> Optional[int]:
|
||||
def content_length(self) -> int | None:
|
||||
# Just a placeholder for adding setter
|
||||
return super().content_length
|
||||
|
||||
@content_length.setter
|
||||
def content_length(self, value: Optional[int]) -> None:
|
||||
def content_length(self, value: int | None) -> None:
|
||||
if value is not None:
|
||||
value = int(value)
|
||||
if self._chunked:
|
||||
|
|
@ -331,12 +333,12 @@ class StreamResponse(BaseClass, HeadersMixin):
|
|||
self._generate_content_type_header()
|
||||
|
||||
@property
|
||||
def charset(self) -> Optional[str]:
|
||||
def charset(self) -> str | None:
|
||||
# Just a placeholder for adding setter
|
||||
return super().charset
|
||||
|
||||
@charset.setter
|
||||
def charset(self, value: Optional[str]) -> None:
|
||||
def charset(self, value: str | None) -> None:
|
||||
ctype = self.content_type # read header values if needed
|
||||
if ctype == "application/octet-stream":
|
||||
raise RuntimeError(
|
||||
|
|
@ -351,7 +353,7 @@ class StreamResponse(BaseClass, HeadersMixin):
|
|||
self._generate_content_type_header()
|
||||
|
||||
@property
|
||||
def last_modified(self) -> Optional[datetime.datetime]:
|
||||
def last_modified(self) -> datetime.datetime | None:
|
||||
"""The value of Last-Modified HTTP header, or None.
|
||||
|
||||
This header is represented as a `datetime` object.
|
||||
|
|
@ -360,7 +362,7 @@ class StreamResponse(BaseClass, HeadersMixin):
|
|||
|
||||
@last_modified.setter
|
||||
def last_modified(
|
||||
self, value: Optional[Union[int, float, datetime.datetime, str]]
|
||||
self, value: int | float | datetime.datetime | str | None
|
||||
) -> None:
|
||||
if value is None:
|
||||
self._headers.pop(hdrs.LAST_MODIFIED, None)
|
||||
|
|
@ -379,7 +381,7 @@ class StreamResponse(BaseClass, HeadersMixin):
|
|||
raise TypeError(msg)
|
||||
|
||||
@property
|
||||
def etag(self) -> Optional[ETag]:
|
||||
def etag(self) -> ETag | None:
|
||||
quoted_value = self._headers.get(hdrs.ETAG)
|
||||
if not quoted_value:
|
||||
return None
|
||||
|
|
@ -395,7 +397,7 @@ class StreamResponse(BaseClass, HeadersMixin):
|
|||
)
|
||||
|
||||
@etag.setter
|
||||
def etag(self, value: Optional[Union[ETag, str]]) -> None:
|
||||
def etag(self, value: ETag | str | None) -> None:
|
||||
if value is None:
|
||||
self._headers.pop(hdrs.ETAG, None)
|
||||
elif (isinstance(value, str) and value == ETAG_ANY) or (
|
||||
|
|
@ -451,7 +453,7 @@ class StreamResponse(BaseClass, HeadersMixin):
|
|||
await self._do_start_compression(coding)
|
||||
return
|
||||
|
||||
async def prepare(self, request: "BaseRequest") -> Optional[AbstractStreamWriter]:
|
||||
async def prepare(self, request: "BaseRequest") -> AbstractStreamWriter | None:
|
||||
if self._eof_sent:
|
||||
return None
|
||||
if self._payload_writer is not None:
|
||||
|
|
@ -494,7 +496,7 @@ class StreamResponse(BaseClass, HeadersMixin):
|
|||
if version != HttpVersion11:
|
||||
raise RuntimeError(
|
||||
"Using chunked encoding is forbidden "
|
||||
"for HTTP/{0.major}.{0.minor}".format(request.version)
|
||||
f"for HTTP/{request.version.major}.{request.version.minor}"
|
||||
)
|
||||
if not self._must_be_empty_body:
|
||||
writer.enable_chunking()
|
||||
|
|
@ -547,7 +549,7 @@ class StreamResponse(BaseClass, HeadersMixin):
|
|||
if self._send_headers_immediately:
|
||||
writer.send_headers()
|
||||
|
||||
async def write(self, data: Union[bytes, bytearray, memoryview]) -> None:
|
||||
async def write(self, data: bytes | bytearray | memoryview) -> None:
|
||||
assert isinstance(
|
||||
data, (bytes, bytearray, memoryview)
|
||||
), "data argument must be byte-ish (%r)" % type(data)
|
||||
|
|
@ -595,19 +597,46 @@ class StreamResponse(BaseClass, HeadersMixin):
|
|||
info = "not prepared"
|
||||
return f"<{self.__class__.__name__} {self.reason} {info}>"
|
||||
|
||||
def __getitem__(self, key: str) -> Any:
|
||||
@overload # type: ignore[override]
|
||||
def __getitem__(self, key: ResponseKey[_T]) -> _T: ...
|
||||
|
||||
@overload
|
||||
def __getitem__(self, key: str) -> Any: ...
|
||||
|
||||
def __getitem__(self, key: str | ResponseKey[_T]) -> Any:
|
||||
return self._state[key]
|
||||
|
||||
def __setitem__(self, key: str, value: Any) -> None:
|
||||
@overload # type: ignore[override]
|
||||
def __setitem__(self, key: ResponseKey[_T], value: _T) -> None: ...
|
||||
|
||||
@overload
|
||||
def __setitem__(self, key: str, value: Any) -> None: ...
|
||||
|
||||
def __setitem__(self, key: str | ResponseKey[_T], value: Any) -> None:
|
||||
if (
|
||||
not isinstance(key, ResponseKey)
|
||||
and key not in StreamResponse._seen_str_keys
|
||||
):
|
||||
# Import here to break circular dependency
|
||||
from .web_exceptions import NotAppKeyWarning
|
||||
|
||||
StreamResponse._seen_str_keys.add(key)
|
||||
warnings.warn(
|
||||
"It is recommended to use web.ResponseKey instances for keys.\n"
|
||||
+ "https://docs.aiohttp.org/en/stable/web_advanced.html"
|
||||
+ "#response-s-storage",
|
||||
category=NotAppKeyWarning,
|
||||
stacklevel=2,
|
||||
)
|
||||
self._state[key] = value
|
||||
|
||||
def __delitem__(self, key: str) -> None:
|
||||
def __delitem__(self, key: str | ResponseKey[_T]) -> None:
|
||||
del self._state[key]
|
||||
|
||||
def __len__(self) -> int:
|
||||
return len(self._state)
|
||||
|
||||
def __iter__(self) -> Iterator[str]:
|
||||
def __iter__(self) -> Iterator[str | ResponseKey[Any]]:
|
||||
return iter(self._state)
|
||||
|
||||
def __hash__(self) -> int:
|
||||
|
|
@ -622,7 +651,7 @@ class StreamResponse(BaseClass, HeadersMixin):
|
|||
|
||||
class Response(StreamResponse):
|
||||
|
||||
_compressed_body: Optional[bytes] = None
|
||||
_compressed_body: bytes | None = None
|
||||
_send_headers_immediately = False
|
||||
|
||||
def __init__(
|
||||
|
|
@ -630,13 +659,13 @@ class Response(StreamResponse):
|
|||
*,
|
||||
body: Any = None,
|
||||
status: int = 200,
|
||||
reason: Optional[str] = None,
|
||||
text: Optional[str] = None,
|
||||
headers: Optional[LooseHeaders] = None,
|
||||
content_type: Optional[str] = None,
|
||||
charset: Optional[str] = None,
|
||||
zlib_executor_size: Optional[int] = None,
|
||||
zlib_executor: Optional[Executor] = None,
|
||||
reason: str | None = None,
|
||||
text: str | None = None,
|
||||
headers: LooseHeaders | None = None,
|
||||
content_type: str | None = None,
|
||||
charset: str | None = None,
|
||||
zlib_executor_size: int = MAX_SYNC_CHUNK_SIZE,
|
||||
zlib_executor: Executor | None = None,
|
||||
) -> None:
|
||||
if body is not None and text is not None:
|
||||
raise ValueError("body and text are not allowed together")
|
||||
|
|
@ -691,7 +720,7 @@ class Response(StreamResponse):
|
|||
self._zlib_executor = zlib_executor
|
||||
|
||||
@property
|
||||
def body(self) -> Optional[Union[bytes, Payload]]:
|
||||
def body(self) -> bytes | bytearray | Payload | None:
|
||||
return self._body
|
||||
|
||||
@body.setter
|
||||
|
|
@ -721,7 +750,7 @@ class Response(StreamResponse):
|
|||
self._compressed_body = None
|
||||
|
||||
@property
|
||||
def text(self) -> Optional[str]:
|
||||
def text(self) -> str | None:
|
||||
if self._body is None:
|
||||
return None
|
||||
# Note: When _body is a Payload (e.g. FilePayload), this may do blocking I/O
|
||||
|
|
@ -744,7 +773,7 @@ class Response(StreamResponse):
|
|||
self._compressed_body = None
|
||||
|
||||
@property
|
||||
def content_length(self) -> Optional[int]:
|
||||
def content_length(self) -> int | None:
|
||||
if self._chunked:
|
||||
return None
|
||||
|
||||
|
|
@ -763,14 +792,14 @@ class Response(StreamResponse):
|
|||
return 0
|
||||
|
||||
@content_length.setter
|
||||
def content_length(self, value: Optional[int]) -> None:
|
||||
def content_length(self, value: int | None) -> None:
|
||||
raise RuntimeError("Content length is set automatically")
|
||||
|
||||
async def write_eof(self, data: bytes = b"") -> None:
|
||||
if self._eof_sent:
|
||||
return
|
||||
if self._compressed_body is None:
|
||||
body: Optional[Union[bytes, Payload]] = self._body
|
||||
body = self._body
|
||||
else:
|
||||
body = self._compressed_body
|
||||
assert not data, f"data arg is not supported, got {data!r}"
|
||||
|
|
@ -779,8 +808,10 @@ class Response(StreamResponse):
|
|||
if body is None or self._must_be_empty_body:
|
||||
await super().write_eof()
|
||||
elif isinstance(self._body, Payload):
|
||||
await self._body.write(self._payload_writer)
|
||||
await self._body.close()
|
||||
try:
|
||||
await self._body.write(self._payload_writer)
|
||||
finally:
|
||||
await self._body.close()
|
||||
await super().write_eof()
|
||||
else:
|
||||
await super().write_eof(cast(bytes, body))
|
||||
|
|
@ -816,13 +847,6 @@ class Response(StreamResponse):
|
|||
executor=self._zlib_executor,
|
||||
)
|
||||
assert self._body is not None
|
||||
if self._zlib_executor_size is None and len(self._body) > LARGE_BODY_SIZE:
|
||||
warnings.warn(
|
||||
"Synchronous compression of large response bodies "
|
||||
f"({len(self._body)} bytes) might block the async event loop. "
|
||||
"Consider providing a custom value to zlib_executor_size/"
|
||||
"zlib_executor response properties or disabling compression on it."
|
||||
)
|
||||
self._compressed_body = (
|
||||
await compressor.compress(self._body) + compressor.flush()
|
||||
)
|
||||
|
|
@ -833,11 +857,11 @@ class Response(StreamResponse):
|
|||
def json_response(
|
||||
data: Any = sentinel,
|
||||
*,
|
||||
text: Optional[str] = None,
|
||||
body: Optional[bytes] = None,
|
||||
text: str | None = None,
|
||||
body: bytes | None = None,
|
||||
status: int = 200,
|
||||
reason: Optional[str] = None,
|
||||
headers: Optional[LooseHeaders] = None,
|
||||
reason: str | None = None,
|
||||
headers: LooseHeaders | None = None,
|
||||
content_type: str = "application/json",
|
||||
dumps: JSONEncoder = json.dumps,
|
||||
) -> Response:
|
||||
|
|
@ -854,3 +878,32 @@ def json_response(
|
|||
headers=headers,
|
||||
content_type=content_type,
|
||||
)
|
||||
|
||||
|
||||
def json_bytes_response(
|
||||
data: Any = sentinel,
|
||||
*,
|
||||
dumps: JSONBytesEncoder,
|
||||
body: bytes | None = None,
|
||||
status: int = 200,
|
||||
reason: str | None = None,
|
||||
headers: LooseHeaders | None = None,
|
||||
content_type: str = "application/json",
|
||||
) -> Response:
|
||||
"""Create a JSON response using a bytes-returning encoder.
|
||||
|
||||
Use this when your JSON encoder (like orjson) returns bytes
|
||||
instead of str, avoiding the encode/decode overhead.
|
||||
"""
|
||||
if data is not sentinel:
|
||||
if body is not None:
|
||||
raise ValueError("only one of data or body should be specified")
|
||||
else:
|
||||
body = dumps(data)
|
||||
return Response(
|
||||
body=body,
|
||||
status=status,
|
||||
reason=reason,
|
||||
headers=headers,
|
||||
content_type=content_type,
|
||||
)
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue