For backwards compatibility, the real_url parameter is optional. """ return tuple.__new__(
cls, (url, method, headers, url if real_url is sentinel else real_url)
)
def __init__(self, fingerprint: bytes) -> None:
digestlen = len(fingerprint)
hashfunc = self.HASHFUNC_BY_DIGESTLEN.get(digestlen) ifnot hashfunc: raise ValueError("fingerprint has invalid length") elif hashfunc is md5 or hashfunc is sha1: raise ValueError("md5 and sha1 are insecure and not supported. Use sha256.")
self._hashfunc = hashfunc
self._fingerprint = fingerprint
if ssl isnotNone:
SSL_ALLOWED_TYPES = (ssl.SSLContext, bool, Fingerprint, type(None)) else: # pragma: no cover
SSL_ALLOWED_TYPES = (bool, type(None))
def _merge_ssl_params(
ssl: Union["SSLContext", bool, Fingerprint],
verify_ssl: Optional[bool],
ssl_context: Optional["SSLContext"],
fingerprint: Optional[bytes],
) -> Union["SSLContext", bool, Fingerprint]: if ssl isNone:
ssl = True# Double check for backwards compatibility if verify_ssl isnotNoneandnot verify_ssl:
warnings.warn( "verify_ssl is deprecated, use ssl=False instead",
DeprecationWarning,
stacklevel=3,
) if ssl isnotTrue: raise ValueError( "verify_ssl, ssl_context, fingerprint and ssl " "parameters are mutually exclusive"
) else:
ssl = False if ssl_context isnotNone:
warnings.warn( "ssl_context is deprecated, use ssl=context instead",
DeprecationWarning,
stacklevel=3,
) if ssl isnotTrue: raise ValueError( "verify_ssl, ssl_context, fingerprint and ssl " "parameters are mutually exclusive"
) else:
ssl = ssl_context if fingerprint isnotNone:
warnings.warn( "fingerprint is deprecated, use ssl=Fingerprint(fingerprint) instead",
DeprecationWarning,
stacklevel=3,
) if ssl isnotTrue: raise ValueError( "verify_ssl, ssl_context, fingerprint and ssl " "parameters are mutually exclusive"
) else:
ssl = Fingerprint(fingerprint) ifnot isinstance(ssl, SSL_ALLOWED_TYPES): raise TypeError( "ssl should be SSLContext, bool, Fingerprint or None, " "got {!r} instead.".format(ssl)
) return ssl
_SSL_SCHEMES = frozenset(("https", "wss"))
# ConnectionKey is a NamedTuple because it is used as a key in a dict # and a set in the connector. Since a NamedTuple is a tuple it uses # the fast native tuple __hash__ and __eq__ implementation in CPython. class ConnectionKey(NamedTuple): # the key should contain an information about used proxy / TLS # to prevent reusing wrong connections from a pool
host: str
port: Optional[int]
is_ssl: bool
ssl: Union[SSLContext, bool, Fingerprint]
proxy: Optional[URL]
proxy_auth: Optional[BasicAuth]
proxy_headers_hash: Optional[int] # hash(CIMultiDict)
def _is_expected_content_type(
response_content_type: str, expected_content_type: str
) -> bool: if expected_content_type == "application/json": return json_re.match(response_content_type) isnotNone return expected_content_type in response_content_type
def _warn_if_unclosed_payload(payload: payload.Payload, stacklevel: int = 2) -> None: """Warn if the payload is not closed.
Callers must check that the body is a Payload before calling this method.
Args:
payload: The payload to check
stacklevel: Stack level for the warning (default 2for direct callers) """ ifnot payload.autoclose andnot payload.consumed:
warnings.warn( "The previous request body contains unclosed resources. " "Use await request.update_body() instead of setting request.body " "directly to properly close resources and avoid leaks.",
ResourceWarning,
stacklevel=stacklevel,
)
class ClientResponse(HeadersMixin):
# Some of these attributes are None when created, # but will be set by the start() method. # As the end user will likely never see the None values, we cheat the types below. # from the Status-Line of the response
version: Optional[HttpVersion] = None# HTTP-Version
status: int = None# type: ignore[assignment] # Status-Code
reason: Optional[str] = None# Reason-Phrase
def __init__(
self,
method: str,
url: URL,
*,
writer: "Optional[asyncio.Task[None]]",
continue100: Optional["asyncio.Future[bool]"],
timer: BaseTimerContext,
request_info: RequestInfo,
traces: List["Trace"],
loop: asyncio.AbstractEventLoop,
session: "ClientSession",
) -> None: # URL forbids subclasses, so a simple type check is enough. assert type(url) is URL
self.method = method
self._real_url = url
self._url = url.with_fragment(None) if url.raw_fragment else url if writer isnotNone:
self._writer = writer if continue100 isnotNone:
self._continue = continue100
self._request_info = request_info
self._timer = timer if timer isnotNoneelse TimerNoop()
self._cache: Dict[str, Any] = {}
self._traces = traces
self._loop = loop # Save reference to _resolve_charset, so that get_encoding() will still # work after the response has finished reading the body. # TODO: Fix session=None in tests (see ClientRequest.__init__). if session isnotNone: # store a reference to session #1985
self._session = session
self._resolve_charset = session._resolve_charset if loop.get_debug():
self._source_traceback = traceback.extract_stack(sys._getframe(1))
_writer is only provided for backwards compatibility for subclasses that may need to access it. """ return self.__writer
@_writer.setter def _writer(self, writer: Optional["asyncio.Task[None]"]) -> None: """Set the writer task for streaming data.""" if self.__writer isnotNone:
self.__writer.remove_done_callback(self.__reset_writer)
self.__writer = writer if writer isNone: return if writer.done(): # The writer is already done, so we can clear it immediately.
self.__writer = None else:
writer.add_done_callback(self.__reset_writer)
@property def cookies(self) -> SimpleCookie: if self._cookies isNone: if self._raw_cookie_headers isnotNone: # Parse cookies for response.cookies (SimpleCookie for backward compatibility)
cookies = SimpleCookie() # Use parse_set_cookie_headers for more lenient parsing that handles # malformed cookies better than SimpleCookie.load
cookies.update(parse_set_cookie_headers(self._raw_cookie_headers))
self._cookies = cookies else:
self._cookies = SimpleCookie() return self._cookies
@cookies.setter def cookies(self, cookies: SimpleCookie) -> None:
self._cookies = cookies # Generate raw cookie headers from the SimpleCookie if cookies:
self._raw_cookie_headers = tuple(
morsel.OutputString() for morsel in cookies.values()
) else:
self._raw_cookie_headers = None
for val in re.split(r",(?=\s*<)", links_str):
match = re.match(r"\s*<(.*)>(.*)", val) if match isNone: # pragma: no cover # the check exists to suppress mypy error continue
url, params_str = match.groups()
params = params_str.split(";")[1:]
link: MultiDict[Union[str, URL]] = MultiDict()
for param in params:
match = re.match(r"^\s*(\S*)\s*=\s*(['\"]?)(.*?)(\2)\s*$", param, re.M) if match isNone: # pragma: no cover # the check exists to suppress mypy error continue
key, _, value, _ = match.groups()
# headers
self._headers = message.headers # type is CIMultiDictProxy
self._raw_headers = message.raw_headers # type is Tuple[bytes, bytes]
# payload
self.content = payload
# cookies if cookie_hdrs := self.headers.getall(hdrs.SET_COOKIE, ()): # Store raw cookie headers for CookieJar
self._raw_cookie_headers = tuple(cookie_hdrs) return self
def _response_eof(self) -> None: if self._closed: return
# protocol could be None because connection could be detached
protocol = self._connection and self._connection.protocol if protocol isnotNoneand protocol.upgraded: return
async def __aexit__(
self,
exc_type: Optional[Type[BaseException]],
exc_val: Optional[BaseException],
exc_tb: Optional[TracebackType],
) -> None:
self._in_context = False # similar to _RequestContextManager, we do not need to check # for exceptions, response object can close connection # if state is broken
self.release()
await self.wait_for_close()
# Type of body depends on PAYLOAD_REGISTRY, which is dynamic.
_body: Union[None, payload.Payload] = None
auth = None
response = None
__writer: Optional["asyncio.Task[None]"] = None# async task for streaming data
# These class defaults help create_autospec() work correctly. # If autospec is improved in future, maybe these can be removed.
url = URL()
method = "GET"
_continue = None# waiter future for '100 Continue' response
# N.B. # Adding __del__ method with self._writer closing doesn't make sense # because _writer is instance method, thus it keeps a reference to self. # Until writer has finished finalizer will not be called.
def __init__(
self,
method: str,
url: URL,
*,
params: Query = None,
headers: Optional[LooseHeaders] = None,
skip_auto_headers: Optional[Iterable[str]] = None,
data: Any = None,
cookies: Optional[LooseCookies] = None,
auth: Optional[BasicAuth] = None,
version: http.HttpVersion = http.HttpVersion11,
compress: Union[str, bool, None] = None,
chunked: Optional[bool] = None,
expect100: bool = False,
loop: Optional[asyncio.AbstractEventLoop] = None,
response_class: Optional[Type["ClientResponse"]] = None,
proxy: Optional[URL] = None,
proxy_auth: Optional[BasicAuth] = None,
timer: Optional[BaseTimerContext] = None,
session: Optional["ClientSession"] = None,
ssl: Union[SSLContext, bool, Fingerprint] = True,
proxy_headers: Optional[LooseHeaders] = None,
traces: Optional[List["Trace"]] = None,
trust_env: bool = False,
server_hostname: Optional[str] = None,
): if loop isNone:
loop = asyncio.get_event_loop() if match := _CONTAINS_CONTROL_CHAR_RE.search(method): raise ValueError(
f"Method cannot contain non-token characters {method!r} "
f"(found at least {match.group()!r})"
) # URL forbids subclasses, so a simple type check is enough. assert type(url) is URL, url if proxy isnotNone: assert type(proxy) is URL, proxy # FIXME: session is None in tests only, need to fix tests # assert session is not None if TYPE_CHECKING: assert session isnotNone
self._session = session if params:
url = url.extend_query(params)
self.original_url = url
self.url = url.with_fragment(None) if url.raw_fragment else url
self.method = method.upper()
self.chunked = chunked
self.compress = compress
self.loop = loop
self.length = None if response_class isNone:
real_response_class = ClientResponse else:
real_response_class = response_class
self.response_class: Type[ClientResponse] = real_response_class
self._timer = timer if timer isnotNoneelse TimerNoop()
self._ssl = ssl if ssl isnotNoneelseTrue
self.server_hostname = server_hostname
if loop.get_debug():
self._source_traceback = traceback.extract_stack(sys._getframe(1))
def _get_content_length(self) -> Optional[int]: """Extract and validate Content-Length header value.
Returns parsed Content-Length value orNoneifnot set.
Raises ValueError if header exists but cannot be parsed as an integer. """ if hdrs.CONTENT_LENGTH notin self.headers: returnNone
@property def body(self) -> Union[payload.Payload, Literal[b""]]: """Request body.""" # empty body is represented as bytes for backwards compatibility return self._body or b""
@body.setter def body(self, value: Any) -> None: """Set request body with warning for non-autoclose payloads.
WARNING: This setter must be called from within an event loop andisnot
thread-safe. Setting body outside of an event loop may raise RuntimeError
when closing file-based payloads.
DEPRECATED: Direct assignment to body is deprecated and will be removed in a future version. Use await update_body() instead for proper resource
management. """ # Close existing payload if present if self._body isnotNone: # Warn if the payload needs manual closing # stacklevel=3: user code -> body setter -> _warn_if_unclosed_payload
_warn_if_unclosed_payload(self._body, stacklevel=3) # NOTE: In the future, when we remove sync close support, # this setter will need to be removed and only the async # update_body() method will be available. For now, we call # _close() for backwards compatibility.
self._body._close()
self._update_body(value)
@property def request_info(self) -> RequestInfo:
headers: CIMultiDictProxy[str] = CIMultiDictProxy(self.headers) # These are created on every request, so we use a NamedTuple # for performance reasons. We don't use the RequestInfo.__new__ # method because it has a different signature which is provided # for backwards compatibility only. return tuple.__new__(
RequestInfo, (self.url, self.method, headers, self.original_url)
)
@property def session(self) -> "ClientSession": """Return the ClientSession instance.
This property provides access to the ClientSession that initiated
this request, allowing middleware to make additional requests
using the same session. """ return self._session
def update_host(self, url: URL) -> None: """Update destination host, port and connection type (ssl).""" # get host/port ifnot url.raw_host: raise InvalidURL(url)
# basic auth info if url.raw_user or url.raw_password:
self.auth = helpers.BasicAuth(url.user or"", url.password or"")
def update_version(self, version: Union[http.HttpVersion, str]) -> None: """Convert request version to two elements tuple.
parser HTTP version '1.1' => (1, 1) """ if isinstance(version, str):
v = [part.strip() for part in version.split(".", 1)] try:
version = http.HttpVersion(int(v[0]), int(v[1])) except ValueError: raise ValueError(
f"Can not parse http version number: {version}"
) fromNone
self.version = version
# Build the host header
host = self.url.host_port_subcomponent
# host_port_subcomponent is None when the URL is a relative URL. # but we know we do not have a relative URL here. assert host isnotNone
self.headers[hdrs.HOST] = host
ifnot headers: return
if isinstance(headers, (dict, MultiDictProxy, MultiDict)):
headers = headers.items()
for key, value in headers: # type: ignore[misc] # A special case for Host header if key in hdrs.HOST_ALL:
self.headers[key] = value else:
self.headers.add(key, value)
def update_auto_headers(self, skip_auto_headers: Optional[Iterable[str]]) -> None: if skip_auto_headers isnotNone:
self._skip_auto_headers = CIMultiDict(
(hdr, None) for hdr in sorted(skip_auto_headers)
)
used_headers = self.headers.copy()
used_headers.extend(self._skip_auto_headers) # type: ignore[arg-type] else: # Fast path when there are no headers to skip # which is the most common case.
used_headers = self.headers
for hdr, val in self.DEFAULT_HEADERS.items(): if hdr notin used_headers:
self.headers[hdr] = val
if hdrs.USER_AGENT notin used_headers:
self.headers[hdrs.USER_AGENT] = SERVER_SOFTWARE
c = SimpleCookie() if hdrs.COOKIE in self.headers: # parse_cookie_header for RFC 6265 compliant Cookie header parsing
c.update(parse_cookie_header(self.headers.get(hdrs.COOKIE, ""))) del self.headers[hdrs.COOKIE]
if isinstance(cookies, Mapping):
iter_cookies = cookies.items() else:
iter_cookies = cookies # type: ignore[assignment] for name, value in iter_cookies: if isinstance(value, Morsel): # Use helper to preserve coded_value exactly as sent by server
c[name] = preserve_morsel_with_coded_value(value) else:
c[name] = value # type: ignore[assignment]
if self.headers.get(hdrs.CONTENT_ENCODING): if self.compress: raise ValueError( "compress can not be set if Content-Encoding header is set"
) elif self.compress: ifnot isinstance(self.compress, str):
self.compress = "deflate"
self.headers[hdrs.CONTENT_ENCODING] = self.compress
self.chunked = True# enable chunked, no need to deal with length
ifnot isinstance(auth, helpers.BasicAuth): raise TypeError("BasicAuth() tuple is required instead")
self.headers[hdrs.AUTHORIZATION] = auth.encode()
def update_body_from_data(self, body: Any, _stacklevel: int = 3) -> None: """Update request body from data.""" if self._body isnotNone:
_warn_if_unclosed_payload(self._body, stacklevel=_stacklevel)
if body isNone:
self._body = None # Set Content-Length to 0 when body is None for methods that expect a body if (
self.method notin self.GET_METHODS andnot self.chunked and hdrs.CONTENT_LENGTH notin self.headers
):
self.headers[hdrs.CONTENT_LENGTH] = "0" return
# FormData
maybe_payload = body() if isinstance(body, FormData) else body
self._body = body_payload # enable chunked encoding if needed ifnot self.chunked and hdrs.CONTENT_LENGTH notin self.headers: if (size := body_payload.size) isnotNone:
self.headers[hdrs.CONTENT_LENGTH] = str(size) else:
self.chunked = True
# copy payload headers assert body_payload.headers
headers = self.headers
skip_headers = self._skip_auto_headers for key, value in body_payload.headers.items(): if key in headers or (skip_headers isnotNoneand key in skip_headers): continue
headers[key] = value
def _update_body(self, body: Any) -> None: """Update request body after its already been set.""" # Remove existing Content-Length header since body is changing if hdrs.CONTENT_LENGTH in self.headers: del self.headers[hdrs.CONTENT_LENGTH]
# Remove existing Transfer-Encoding header to avoid conflicts if self.chunked and hdrs.TRANSFER_ENCODING in self.headers: del self.headers[hdrs.TRANSFER_ENCODING]
# Now update the body using the existing method # Called from _update_body, add 1 to stacklevel from caller
self.update_body_from_data(body, _stacklevel=4)
# Update transfer encoding headers if needed (same logic as __init__) if body isnotNoneor self.method notin self.GET_METHODS:
self.update_transfer_encoding()
async def update_body(self, body: Any) -> None: """
Update request body and close previous payload if needed.
This method safely updates the request body by first closing any existing
payload to prevent resource leaks, then setting the new body.
IMPORTANT: Always use this method instead of setting request.body directly.
Direct assignment to request.body will leak resources if the previous body
contains file handles, streams, or other resources that need cleanup.
Args:
body: The new body content. Can be:
- bytes/bytearray: Raw binary data
- str: Text data (will be encoded using charset from Content-Type)
- FormData: Form data that will be encoded as multipart/form-data
- Payload: A pre-configured payload object
- AsyncIterable: An async iterable of bytes chunks
- File-like object: Will be read and sent as binary data
- None: Clears the body
Usage: # CORRECT: Use update_body
await request.update_body(b"new request data")
# WRONG: Don't set body directly # request.body = b"new request data" # This will leak resources!
# Update with form data
form_data = FormData()
form_data.add_field('field', 'value')
await request.update_body(form_data)
# Clear body
await request.update_body(None)
Note:
This method is async because it may need to close file handles or
other resources associated with the previous payload. Always await
this method to ensure proper cleanup.
Warning:
Setting request.body directly is highly discouraged and can lead to:
- Resource leaks (unclosed file handles, streams)
- Memory leaks (unreleased buffers)
- Unexpected behavior with streaming payloads
It isnot recommended to change the payload type in middleware. If the
body was already set (e.g., as bytes), it's best to keep the same type
rather than converting it (e.g., to str) as this may result in unexpected
behavior.
See Also:
- update_body_from_data: Synchronous body update without cleanup
- body property: Direct body access (STRONGLY DISCOURAGED)
""" # Close existing payload if it exists and needs closing if self._body isnotNone:
await self._body.close()
self._update_body(body)
def update_expect_continue(self, expect: bool = False) -> None: if expect:
self.headers[hdrs.EXPECT] = "100-continue" elif (
hdrs.EXPECT in self.headers and self.headers[hdrs.EXPECT].lower() == "100-continue"
):
expect = True
if expect:
self._continue = self.loop.create_future()
if proxy_auth andnot isinstance(proxy_auth, helpers.BasicAuth): raise ValueError("proxy_auth must be None or BasicAuth() tuple")
self.proxy_auth = proxy_auth
async def write_bytes(
self,
writer: AbstractStreamWriter,
conn: "Connection",
content_length: Optional[int] = None,
) -> None: """
Write the request body to the connection stream.
This method handles writing different types of request bodies: 1. Payload objects (using their specialized write_with_length method) 2. Bytes/bytearray objects 3. Iterable body content
Args:
writer: The stream writer to write the body to
conn: The connection being used for this request
content_length: Optional maximum number of bytes to write from the body
(None means write the entire body)
The method properly handles:
- Waiting for100-Continue responses if required
- Content length constraints for chunked encoding
- Error handling for network issues, cancellation, and other exceptions
- Signaling EOF and timeout management
Raises:
ClientOSError: When there's an OS-level error writing the body
ClientConnectionError: When there's a general connection error
asyncio.CancelledError: When the operation is cancelled
""" # 100 response if self._continueisnotNone: # Force headers to be sent before waiting for 100-continue
writer.send_headers()
await writer.drain()
await self._continue
protocol = conn.protocol assert protocol isnotNone try: # This should be a rare case but the # self._body can be set to None while # the task is being started or we wait above # for the 100-continue response. # The more likely case is we have an empty # payload, but 100-continue is still expected. if self._body isnotNone:
await self._body.write_with_length(writer, content_length) except OSError as underlying_exc:
reraised_exc = underlying_exc
# Distinguish between timeout and other OS errors for better error reporting
exc_is_not_timeout = underlying_exc.errno isnotNoneornot isinstance(
underlying_exc, asyncio.TimeoutError
) if exc_is_not_timeout:
reraised_exc = ClientOSError(
underlying_exc.errno,
f"Can not write request body for {self.url !s}",
)
set_exception(protocol, reraised_exc, underlying_exc) except asyncio.CancelledError: # Body hasn't been fully sent, so connection can't be reused
conn.close() raise except Exception as underlying_exc:
set_exception(
protocol,
ClientConnectionError( "Failed to send bytes into the underlying connection "
f"{conn !s}: {underlying_exc!r}",
),
underlying_exc,
) else: # Successfully wrote the body, signal EOF and start response timeout
await writer.write_eof()
protocol.start_timeout()
async def send(self, conn: "Connection") -> "ClientResponse": # Specify request target: # - CONNECT request must send authority form URI # - not CONNECT proxy must send absolute form URI # - most common is origin form URI if self.method == hdrs.METH_CONNECT:
connect_host = self.url.host_subcomponent assert connect_host isnotNone
path = f"{connect_host}:{self.url.port}" elif self.proxy andnot self.is_ssl():
path = str(self.url) else:
path = self.url.raw_path_qs
if self.compress:
writer.enable_compression(self.compress) # type: ignore[arg-type]
if self.chunked isnotNone:
writer.enable_chunking()
# set default content-type if (
self.method in self.POST_METHODS and (
self._skip_auto_headers isNone or hdrs.CONTENT_TYPE notin self._skip_auto_headers
) and hdrs.CONTENT_TYPE notin self.headers
):
self.headers[hdrs.CONTENT_TYPE] = "application/octet-stream"
v = self.version if hdrs.CONNECTION notin self.headers: if conn._connector.force_close: if v == HttpVersion11:
self.headers[hdrs.CONNECTION] = "close" elif v == HttpVersion10:
self.headers[hdrs.CONNECTION] = "keep-alive"
# status + headers
status_line = f"{self.method} {path} HTTP/{v.major}.{v.minor}"
# Buffer headers for potential coalescing with body
await writer.write_headers(status_line, self.headers)
task: Optional["asyncio.Task[None]"] if self._body or self._continueisnotNoneor protocol.writing_paused:
coro = self.write_bytes(writer, conn, self._get_content_length()) if sys.version_info >= (3, 12): # Optimization for Python 3.12, try to write # bytes immediately to avoid having to schedule # the task on the event loop.
task = asyncio.Task(coro, loop=self.loop, eager_start=True) else:
task = self.loop.create_task(coro) if task.done():
task = None else:
self._writer = task else: # We have nothing to write because # - there is no body # - the protocol does not have writing paused # - we are not waiting for a 100-continue response
protocol.start_timeout()
writer.set_eof()
task = None
response_class = self.response_class assert response_class isnotNone
self.response = response_class(
self.method,
self.original_url,
writer=task,
continue100=self._continue,
timer=self._timer,
request_info=self.request_info,
traces=self._traces,
loop=self.loop,
session=self._session,
) return self.response
async def close(self) -> None: if self.__writer isnotNone: try:
await self.__writer except asyncio.CancelledError: if (
sys.version_info >= (3, 11) and (task := asyncio.current_task()) and task.cancelling()
): raise
Die Informationen auf dieser Webseite wurden
nach bestem Wissen sorgfältig zusammengestellt. Es wird jedoch weder Vollständigkeit, noch Richtigkeit,
noch Qualität der bereit gestellten Informationen zugesichert.
Bemerkung:
Die farbliche Syntaxdarstellung und die Messung sind noch experimentell.