Skip to content
Myr

Add inline types to Requests (#7272)

Before adoption: this commit came in with the history the project adopted, so no landing records it.

authored by Nate Prewitt · committed by GitHub · parent 8f6cda9 · Browse files · 20 files+1308 added−525 removed
This commit

State

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Diff stats

20 files+1308 added−525 removed

  • tests:+1 added−0 removed
  • other:+1307 added−525 removed

20 files+1308 added−525 removed

added:.github/workflows/typecheck.yml+32 added
modified:src/requests/__init__.py+53 added-17 removed
36 unmodified lines
37:copyright: (c) 2017 by Kenneth Reitz.38:license: Apache 2.0, see LICENSE for more details.39"""4041from __future__ import annotations4243import warnings4445import urllib346
4 unmodified lines
51except ImportError:52 charset_normalizer_version = None5354try:53 from chardet import __version__ as chardet_version55 from chardet import __version__ as chardet_version # type: ignore[import-not-found]56except ImportError:57 chardet_version = None585958def check_compatibility(urllib3_version, chardet_version, charset_normalizer_version):59 urllib3_version = urllib3_version.split(".")[:3]60 assert urllib3_version != ["dev"] # Verify urllib3 isn't installed from git.60def check_compatibility(61 urllib3_version: str,62 chardet_version: str | None,63 charset_normalizer_version: str | None,64) -> None:65 urllib3_version_list = urllib3_version.split(".")[:3]66 assert urllib3_version_list != ["dev"] # Verify urllib3 isn't installed from git.6768 # Sometimes, urllib3 only reports its version as 16.1.63 if len(urllib3_version) == 2:64 urllib3_version.append("0")69 if len(urllib3_version_list) == 2:70 urllib3_version_list.append("0")7172 # Check urllib3 for compatibility.67 major, minor, patch = urllib3_version # noqa: F81173 major, minor, patch = urllib3_version_list # noqa: F81174 major, minor, patch = int(major), int(minor), int(patch)75 # urllib3 >= 1.21.176 assert major >= 177 if major == 1:
17 unmodified lines
95 RequestsDependencyWarning,96 )979893def _check_cryptography(cryptography_version):99def _check_cryptography(cryptography_version: str) -> None:100 # cryptography < 1.3.4101 try:96 cryptography_version = list(map(int, cryptography_version.split(".")))102 cryptography_version_list = list(map(int, cryptography_version.split(".")))103 except ValueError:104 return105100 if cryptography_version < [1, 3, 4]:101 warning = (102 f"Old version of cryptography ({cryptography_version}) may cause slowdown."103 )106 if cryptography_version_list < [1, 3, 4]:107 warning = f"Old version of cryptography ({cryptography_version_list}) may cause slowdown."108 warnings.warn(warning, RequestsDependencyWarning)109110111# Check imported dependencies for compatibility.112try:113 check_compatibility(110 urllib3.__version__, chardet_version, charset_normalizer_version114 urllib3.__version__, # type: ignore[reportPrivateImportUsage]115 chardet_version, # type: ignore[reportUnknownArgumentType]116 charset_normalizer_version,117 )118except (AssertionError, ValueError):119 warnings.warn(114 f"urllib3 ({urllib3.__version__}) or chardet "120 f"urllib3 ({urllib3.__version__}) or chardet " # type: ignore[reportPrivateImportUsage]121 f"({chardet_version})/charset_normalizer ({charset_normalizer_version}) "122 "doesn't match a supported version!",123 RequestsDependencyWarning,124 )
12 unmodified lines
137138 pyopenssl.inject_into_urllib3()139140 # Check cryptography version135 from cryptography import __version__ as cryptography_version141 from cryptography import ( # type: ignore[reportMissingImports]142 __version__ as cryptography_version, # type: ignore[reportUnknownVariableType]143 )144137 _check_cryptography(cryptography_version)145 _check_cryptography(cryptography_version) # type: ignore[reportUnknownArgumentType]146except ImportError:147 pass148149# urllib3's DependencyWarnings should be silenced.
34 unmodified lines
184from .models import PreparedRequest, Request, Response185from .sessions import Session, session186from .status_codes import codes187188__all__ = (189 "ConnectionError",190 "ConnectTimeout",191 "HTTPError",192 "JSONDecodeError",193 "PreparedRequest",194 "ReadTimeout",195 "Request",196 "RequestException",197 "Response",198 "Session",199 "Timeout",200 "TooManyRedirects",201 "URLRequired",202 "codes",203 "delete",204 "get",205 "head",206 "options",207 "packages",208 "patch",209 "post",210 "put",211 "request",212 "session",213 "utils",214)215216logging.getLogger(__name__).addHandler(NullHandler())217218# FileModeWarnings go off per the default.219warnings.simplefilter("default", FileModeWarning, append=True)
modified:src/requests/_internal_utils.py+2 added-2 removed
21 unmodified lines
22 str: _HEADER_VALIDATORS_STR,23}242526def to_native_string(string, encoding="ascii"):26def to_native_string(string: str | bytes, encoding: str = "ascii") -> str:27 """Given a string object, regardless of type, returns a representation of28 that string in the native string type, encoding and decoding where29 necessary. This assumes ASCII unless told otherwise.30 """
4 unmodified lines
3536 return out373839def unicode_is_ascii(u_string):39def unicode_is_ascii(u_string: str) -> bool:40 """Determine if unicode string only contains ASCII characters.4142 :param str u_string: unicode string to check. Must be unicode43 and not Python 2 `str`.
8 unmodified lines
added:src/requests/_types.py+176 added
1"""2requests._types3~~~~~~~~~~~~~~~45This module contains type aliases used internally by the Requests library.6These types are not part of the public API and must not be relied upon7by external code.8"""910from __future__ import annotations1112from collections.abc import Callable, Iterable, Mapping, MutableMapping13from typing import (14 TYPE_CHECKING,15 Any,16 Protocol,17 TypeAlias,18 TypeVar,19 runtime_checkable,20)2122_T_co = TypeVar("_T_co", covariant=True)232425@runtime_checkable26class SupportsRead(Protocol[_T_co]):27 def read(self, length: int = ..., /) -> _T_co: ...282930@runtime_checkable31class SupportsItems(Protocol):32 def items(self) -> Iterable[tuple[Any, Any]]: ...333435# These are needed at runtime for default_hooks() return type36HookType: TypeAlias = Callable[["Response"], Any]37HooksInputType: TypeAlias = Mapping[str, Iterable[HookType] | HookType]383940def is_prepared(request: PreparedRequest) -> TypeIs[_ValidatedRequest]:41 """Verify a PreparedRequest has been fully prepared."""42 if TYPE_CHECKING:43 return request.url is not None and request.method is not None44 # noop at runtime to avoid AssertionError45 return True464748if TYPE_CHECKING:49 from http.cookiejar import CookieJar50 from typing import TypeAlias, TypedDict5152 from typing_extensions import (53 Buffer, # TODO: move to collections.abc when Python >= 3.1254 TypeIs, # TODO: move to typing when Python >= 3.1355 )5657 from .auth import AuthBase58 from .cookies import RequestsCookieJar59 from .models import PreparedRequest, Response60 from .structures import CaseInsensitiveDict6162 class _ValidatedRequest(PreparedRequest):63 """Subtype asserting a PreparedRequest has been fully prepared before calling.6465 The override suppression is required because mutable attribute types are66 invariant (Liskov), but we only narrow after preparation is complete. This67 is the explicit contract for Requests but Python's typing doesn't have a68 better way to represent the requirement.69 """7071 url: str # type: ignore[reportIncompatibleVariableOverride]72 method: str # type: ignore[reportIncompatibleVariableOverride]7374 # Type aliases for core API concepts (ordered by request() signature)75 UriType: TypeAlias = str | bytes7677 _ParamsMappingKeyType: TypeAlias = str | bytes | int | float78 _ParamsMappingValueType: TypeAlias = (79 str | bytes | int | float | Iterable[str | bytes | int | float] | None80 )81 ParamsType: TypeAlias = (82 Mapping[_ParamsMappingKeyType, _ParamsMappingValueType]83 | tuple[tuple[_ParamsMappingKeyType, _ParamsMappingValueType], ...]84 | Iterable[tuple[_ParamsMappingKeyType, _ParamsMappingValueType]]85 | str86 | bytes87 | None88 )8990 KVDataType: TypeAlias = Iterable[tuple[Any, Any]] | Mapping[Any, Any]9192 RawDataType: TypeAlias = KVDataType | str | bytes93 StreamDataType: TypeAlias = SupportsRead[str | bytes]94 EncodableDataType: TypeAlias = RawDataType | StreamDataType9596 DataType: TypeAlias = (97 KVDataType98 | Iterable[bytes | str]99 | str100 | bytes101 | Buffer102 | SupportsRead[str | bytes]103 | None104 )105106 BodyType: TypeAlias = (107 bytes | str | Iterable[bytes | str] | SupportsRead[bytes | str] | None108 )109110 HeadersType: TypeAlias = CaseInsensitiveDict[str] | Mapping[str, str | bytes]111 HeadersUpdateType: TypeAlias = Mapping[str, str | bytes | None]112113 CookiesType: TypeAlias = RequestsCookieJar | Mapping[str, str]114115 # Building blocks for FilesType116 _FileName: TypeAlias = str | None117 _FileContent: TypeAlias = SupportsRead[str | bytes] | str | bytes118 _FileSpecBasic: TypeAlias = tuple[_FileName, _FileContent]119 _FileSpecWithContentType: TypeAlias = tuple[_FileName, _FileContent, str]120 _FileSpecWithHeaders: TypeAlias = tuple[121 _FileName, _FileContent, str, CaseInsensitiveDict[str] | Mapping[str, str]122 ]123 _FileSpec: TypeAlias = (124 _FileContent | _FileSpecBasic | _FileSpecWithContentType | _FileSpecWithHeaders125 )126 FilesType: TypeAlias = (127 Mapping[str, _FileSpec] | Iterable[tuple[str, _FileSpec]] | None128 )129130 AuthType: TypeAlias = (131 tuple[str, str] | AuthBase | Callable[[PreparedRequest], PreparedRequest] | None132 )133134 TimeoutType: TypeAlias = float | tuple[float | None, float | None] | None135 ProxiesType: TypeAlias = MutableMapping[str, str]136 HooksType: TypeAlias = dict[str, list[HookType]] | None137 VerifyType: TypeAlias = bool | str138 CertType: TypeAlias = str | tuple[str, str] | None139 JsonType: TypeAlias = (140 None | bool | int | float | str | list["JsonType"] | dict[str, "JsonType"]141 )142143 # TypedDicts for Unpack kwargs (PEP 692)144145 class BaseRequestKwargs(TypedDict, total=False):146 headers: Mapping[str, str | bytes] | None147 cookies: RequestsCookieJar | CookieJar | dict[str, str] | None148 files: FilesType149 auth: AuthType150 timeout: TimeoutType151 allow_redirects: bool152 proxies: dict[str, str] | None153 hooks: HooksType154 stream: bool | None155 verify: VerifyType | None156 cert: CertType157158 class RequestKwargs(BaseRequestKwargs, total=False):159 """kwargs for request(), options(), head(), delete()."""160161 params: ParamsType162 data: DataType163 json: JsonType164165 class GetKwargs(BaseRequestKwargs, total=False):166 data: DataType167 json: JsonType168169 class PostKwargs(BaseRequestKwargs, total=False):170 params: ParamsType171172 class DataKwargs(BaseRequestKwargs, total=False):173 """kwargs for put(), patch()."""174175 params: ParamsType176 json: JsonType
modified:src/requests/adapters.py+100 added-47 removed
4 unmodified lines
5This module contains the transport adapters that Requests uses to define6and maintain connections.7"""89from __future__ import annotations1011import os.path10import socket # noqa: F40112import socket # noqa: F401 # type: ignore[reportUnusedImport]13import typing14import warnings15from typing import Any1617from urllib3.exceptions import (18 ClosedPoolError,19 ConnectTimeoutError,
12 unmodified lines
32from urllib3.util import Timeout as TimeoutSauce33from urllib3.util import parse_url34from urllib3.util.retry import Retry3533from .auth import _basic_auth_str36from .auth import _basic_auth_str # type: ignore[reportPrivateUsage]37from .compat import basestring, urlparse38from .cookies import extract_cookies_to_jar39from .exceptions import (40 ConnectionError,
18 unmodified lines
59 urldefragauth,60)6162try:60 from urllib3.contrib.socks import SOCKSProxyManager63 from urllib3.contrib.socks import SOCKSProxyManager # type: ignore[assignment]64except ImportError:6563 def SOCKSProxyManager(*args, **kwargs):66 def SOCKSProxyManager(*args: Any, **kwargs: Any) -> None:67 raise InvalidSchema("Missing dependencies for SOCKS support.")686970if typing.TYPE_CHECKING:71 from urllib3.connectionpool import HTTPConnectionPool72 from urllib3.poolmanager import PoolManager as _PoolManager7374 from . import _types as _t75 from .models import PreparedRequest7677from ._types import is_prepared as _is_prepared7879DEFAULT_POOLBLOCK = False80DEFAULT_POOLSIZE = 1081DEFAULT_RETRIES = 082DEFAULT_POOL_TIMEOUT = None838485def _urllib3_request_context(78 request: "PreparedRequest",79 verify: "bool | str | None",80 client_cert: "tuple[str, str] | str | None",81 poolmanager: "PoolManager",82) -> "(dict[str, typing.Any], dict[str, typing.Any])":83 host_params = {}84 pool_kwargs = {}86 request: PreparedRequest,87 verify: bool | str | None,88 client_cert: tuple[str, str] | str | None,89 poolmanager: PoolManager,90) -> tuple[dict[str, Any], dict[str, Any]]:91 host_params: dict[str, Any] = {}92 pool_kwargs: dict[str, Any] = {}93 parsed_request_url = urlparse(request.url)94 scheme = parsed_request_url.scheme.lower()95 port = parsed_request_url.port96
24 unmodified lines
121122class BaseAdapter:123 """The Base Transport Adapter"""124117 def __init__(self):125 def __init__(self) -> None:126 super().__init__()127128 def send(121 self, request, stream=False, timeout=None, verify=True, cert=None, proxies=None122 ):129 self,130 request: PreparedRequest,131 stream: bool = False,132 timeout: _t.TimeoutType = None,133 verify: _t.VerifyType = True,134 cert: _t.CertType = None,135 proxies: dict[str, str] | None = None,136 ) -> Response:137 """Sends PreparedRequest object. Returns Response object.138139 :param request: The :class:`PreparedRequest <PreparedRequest>` being sent.140 :param stream: (optional) Whether to stream the request content.
8 unmodified lines
149 :param proxies: (optional) The proxies dictionary to apply to the request.150 """151 raise NotImplementedError152139 def close(self):153 def close(self) -> None:154 """Cleans up adapter specific items."""155 raise NotImplementedError156157
23 unmodified lines
181 >>> a = requests.adapters.HTTPAdapter(max_retries=3)182 >>> s.mount('http://', a)183 """184171 __attrs__ = [185 __attrs__: list[str] = [186 "max_retries",187 "config",188 "_pool_connections",189 "_pool_maxsize",190 "_pool_block",191 ]192193 max_retries: Retry194 config: dict[str, Any]195 proxy_manager: dict[str, Any]196 _pool_connections: int197 _pool_maxsize: int198 _pool_block: bool199 poolmanager: _PoolManager200201 def __init__(202 self,181 pool_connections=DEFAULT_POOLSIZE,182 pool_maxsize=DEFAULT_POOLSIZE,183 max_retries=DEFAULT_RETRIES,184 pool_block=DEFAULT_POOLBLOCK,185 ):203 pool_connections: int = DEFAULT_POOLSIZE,204 pool_maxsize: int = DEFAULT_POOLSIZE,205 max_retries: int | Retry = DEFAULT_RETRIES,206 pool_block: bool = DEFAULT_POOLBLOCK,207 ) -> None:208 if max_retries == DEFAULT_RETRIES:209 self.max_retries = Retry(0, read=False)210 else:211 self.max_retries = Retry.from_int(max_retries)
7 unmodified lines
219 self._pool_block = pool_block220221 self.init_poolmanager(pool_connections, pool_maxsize, block=pool_block)222201 def __getstate__(self):223 def __getstate__(self) -> dict[str, Any]:224 return {attr: getattr(self, attr, None) for attr in self.__attrs__}225204 def __setstate__(self, state):226 def __setstate__(self, state: dict[str, Any]) -> None:227 # Can't handle by adding 'proxy_manager' to self.__attrs__ because228 # self.poolmanager uses a lambda function, which isn't pickleable.229 self.proxy_manager = {}230 self.config = {}
5 unmodified lines
236 self._pool_connections, self._pool_maxsize, block=self._pool_block237 )238239 def init_poolmanager(218 self, connections, maxsize, block=DEFAULT_POOLBLOCK, **pool_kwargs219 ):240 self,241 connections: int,242 maxsize: int,243 block: bool = DEFAULT_POOLBLOCK,244 **pool_kwargs: Any,245 ) -> None:246 """Initializes a urllib3 PoolManager.247248 This method should not be called from user code, and is only249 exposed for use when subclassing the
15 unmodified lines
265 block=block,266 **pool_kwargs,267 )268243 def proxy_manager_for(self, proxy, **proxy_kwargs):269 def proxy_manager_for(self, proxy: str, **proxy_kwargs: Any) -> Any:270 """Return urllib3 ProxyManager for the given proxy.271272 This method should not be called from user code, and is only273 exposed for use when subclassing the
29 unmodified lines
303 )304305 return manager306281 def cert_verify(self, conn, url, verify, cert):307 def cert_verify(308 self, conn: Any, url: str, verify: _t.VerifyType, cert: _t.CertType309 ) -> None:310 """Verify a SSL certificate. This method should not be called from user311 code, and is only exposed for use when subclassing the312 :class:`HTTPAdapter <requests.adapters.HTTPAdapter>`.313
47 unmodified lines
361 raise OSError(362 f"Could not find the TLS key file, invalid path: {conn.key_file}"363 )364337 def build_response(self, req, resp):365 def build_response(self, req: PreparedRequest, resp: Any) -> Response:366 """Builds a :class:`Response <requests.Response>` object from a urllib3367 response. This should not be called from user code, and is only exposed368 for use when subclassing the369 :class:`HTTPAdapter <requests.adapters.HTTPAdapter>`
1 unmodified line
371 :param req: The :class:`PreparedRequest <PreparedRequest>` used to generate the response.372 :param resp: The urllib3 response object.373 :rtype: requests.Response374 """375 assert _is_prepared(req)376 response = Response()377378 # Fallback to None if there's no status_code, for whatever reason.350 response.status_code = getattr(resp, "status", None)379 response.status_code = getattr(resp, "status", None) # type: ignore[assignment]380381 # Make headers case-insensitive.382 response.headers = CaseInsensitiveDict(getattr(resp, "headers", {}))383
15 unmodified lines
399 response.connection = self400401 return response402374 def build_connection_pool_key_attributes(self, request, verify, cert=None):403 def build_connection_pool_key_attributes(404 self, request: PreparedRequest, verify: _t.VerifyType, cert: _t.CertType = None405 ) -> tuple[dict[str, Any], dict[str, Any]]:406 """Build the PoolKey attributes used by urllib3 to return a connection.407408 This looks at the PreparedRequest, the user-specified verify value,409 and the value of the cert parameter to determine what PoolKey values
41 unmodified lines
451 second is a dictionary of SSLContext related parameters.452 """453 return _urllib3_request_context(request, verify, cert, self.poolmanager)454424 def get_connection_with_tls_context(self, request, verify, proxies=None, cert=None):455 def get_connection_with_tls_context(456 self,457 request: PreparedRequest,458 verify: _t.VerifyType,459 proxies: dict[str, str] | None = None,460 cert: _t.CertType = None,461 ) -> HTTPConnectionPool:462 """Returns a urllib3 connection for the given request and TLS settings.463 This should not be called from user code, and is only exposed for use464 when subclassing the :class:`HTTPAdapter <requests.adapters.HTTPAdapter>`.465
9 unmodified lines
475 :param cert:476 (optional) Any user-provided SSL certificate to be used for client477 authentication (a.k.a., mTLS).478 :rtype:442 urllib3.ConnectionPool479 urllib3.HTTPConnectionPool480 """481 assert _is_prepared(request)482483 proxy = select_proxy(request.url, proxies)484 try:485 host_params, pool_kwargs = self.build_connection_pool_key_attributes(486 request,
21 unmodified lines
508 )509510 return conn511473 def get_connection(self, url, proxies=None):512 def get_connection(513 self, url: str, proxies: dict[str, str] | None = None514 ) -> HTTPConnectionPool:515 """DEPRECATED: Users should move to `get_connection_with_tls_context`516 for all subclasses of HTTPAdapter using Requests>=2.32.2.517518 Returns a urllib3 connection for the given URL. This should not be
1 unmodified line
520 :class:`HTTPAdapter <requests.adapters.HTTPAdapter>`.521522 :param url: The URL to connect to.523 :param proxies: (optional) A Requests-style dictionary of proxies used on this request.483 :rtype: urllib3.ConnectionPool524 :rtype: urllib3.HTTPConnectionPool525 """526 warnings.warn(527 (528 "`get_connection` has been deprecated in favor of "
22 unmodified lines
551 conn = self.poolmanager.connection_from_url(url)552553 return conn554514 def close(self):555 def close(self) -> None:556 """Disposes of any internal state.557558 Currently, this closes the PoolManager and any active ProxyManager,559 which closes any pooled connections.
1 unmodified line
561 self.poolmanager.clear()562 for proxy in self.proxy_manager.values():563 proxy.clear()564524 def request_url(self, request, proxies):565 def request_url(566 self, request: PreparedRequest, proxies: dict[str, str] | None567 ) -> str:568 """Obtain the url to use when making the final request.569570 If the message is being sent through a HTTP proxy, the full URL has to571 be used. Otherwise, we should only use the path portion of the URL.
5 unmodified lines
577 :param request: The :class:`PreparedRequest <PreparedRequest>` being sent.578 :param proxies: A dictionary of schemes or schemes and hosts to proxy URLs.579 :rtype: str580 """581 assert _is_prepared(request)582583 proxy = select_proxy(request.url, proxies)584 scheme = urlparse(request.url).scheme585586 is_proxied_http_request = proxy and scheme != "https"
10 unmodified lines
597 url = urldefragauth(request.url)598599 return url600556 def add_headers(self, request, **kwargs):601 def add_headers(self, request: PreparedRequest, **kwargs: Any) -> None:602 """Add any headers needed by the connection. As of v2.0 this does603 nothing by default, but is left for overriding by users that subclass604 the :class:`HTTPAdapter <requests.adapters.HTTPAdapter>`.605
5 unmodified lines
611 :param kwargs: The keyword arguments from the call to send().612 """613 pass614570 def proxy_headers(self, proxy):615 def proxy_headers(self, proxy: str) -> dict[str, str]:616 """Returns a dictionary of the headers to add to any request sent617 through a proxy. This works with urllib3 magic to ensure that they are618 correctly sent to the proxy, rather than in a tunnelled request if619 CONNECT is being used.
4 unmodified lines
624625 :param proxy: The url of the proxy being used for this request.626 :rtype: dict627 """583 headers = {}628 headers: dict[str, str] = {}629 username, password = get_auth_from_url(proxy)630631 if username:632 headers["Proxy-Authorization"] = _basic_auth_str(username, password)633634 return headers635636 def send(592 self, request, stream=False, timeout=None, verify=True, cert=None, proxies=None593 ):637 self,638 request: PreparedRequest,639 stream: bool = False,640 timeout: _t.TimeoutType = None,641 verify: _t.VerifyType = True,642 cert: _t.CertType = None,643 proxies: dict[str, str] | None = None,644 ) -> Response:645 """Sends PreparedRequest object. Returns Response object.646647 :param request: The :class:`PreparedRequest <PreparedRequest>` being sent.648 :param stream: (optional) Whether to stream the request content.
8 unmodified lines
657 :param proxies: (optional) The proxies dictionary to apply to the request.658 :rtype: requests.Response659 """660661 assert _is_prepared(request)662663 try:664 conn = self.get_connection_with_tls_context(665 request, verify, proxies=proxies, cert=cert666 )
15 unmodified lines
682683 if isinstance(timeout, tuple):684 try:685 connect, read = timeout633 timeout = TimeoutSauce(connect=connect, read=read)686 resolved_timeout = TimeoutSauce(connect=connect, read=read)687 except ValueError:688 raise ValueError(689 f"Invalid timeout {timeout}. Pass a (connect, read) timeout tuple, "690 f"or a single float to set both timeouts to the same value."691 )692 elif isinstance(timeout, TimeoutSauce):640 pass693 resolved_timeout = timeout694 else:642 timeout = TimeoutSauce(connect=timeout, read=timeout)695 resolved_timeout = TimeoutSauce(connect=timeout, read=timeout)696697 try:698 resp = conn.urlopen(699 method=request.method,700 url=url,648 body=request.body,649 headers=request.headers,701 body=request.body, # type: ignore[arg-type] # urllib3 stubs don't accept Iterable[bytes | str]702 headers=request.headers, # type: ignore[arg-type] # urllib3#3072703 redirect=False,704 assert_same_host=False,705 preload_content=False,706 decode_content=False,707 retries=self.max_retries,655 timeout=timeout,708 timeout=resolved_timeout,709 chunked=chunked,710 )711712 except (ProtocolError, OSError) as err:
38 unmodified lines
modified:src/requests/api.py+31 added-8 removed
6 unmodified lines
7:copyright: (c) 2012 by Kenneth Reitz.8:license: Apache2, see LICENSE for more details.9"""1011from __future__ import annotations1213from typing import TYPE_CHECKING1415from . import sessions16from .models import Response1718if TYPE_CHECKING:19 from typing_extensions import Unpack2014def request(method, url, **kwargs):21 from . import _types as _t222324def request(25 method: str, url: _t.UriType, **kwargs: Unpack[_t.RequestKwargs]26) -> Response:27 """Constructs and sends a :class:`Request <Request>`.2829 :param method: method for the new :class:`Request` object: ``GET``, ``OPTIONS``, ``HEAD``, ``POST``, ``PUT``, ``PATCH``, or ``DELETE``.30 :param url: URL for the new :class:`Request` object.
39 unmodified lines
70 with sessions.Session() as session:71 return session.request(method=method, url=url, **kwargs)727362def get(url, params=None, **kwargs):74def get(75 url: _t.UriType, params: _t.ParamsType = None, **kwargs: Unpack[_t.GetKwargs]76) -> Response:77 r"""Sends a GET request.7879 :param url: URL for the new :class:`Request` object.80 :param params: (optional) Dictionary, list of tuples or bytes to send
5 unmodified lines
8687 return request("get", url, params=params, **kwargs)888976def options(url, **kwargs):90def options(url: _t.UriType, **kwargs: Unpack[_t.RequestKwargs]) -> Response:91 r"""Sends an OPTIONS request.9293 :param url: URL for the new :class:`Request` object.94 :param \*\*kwargs: Optional arguments that ``request`` takes.
3 unmodified lines
9899 return request("options", url, **kwargs)10010188def head(url, **kwargs):102def head(url: _t.UriType, **kwargs: Unpack[_t.RequestKwargs]) -> Response:103 r"""Sends a HEAD request.104105 :param url: URL for the new :class:`Request` object.106 :param \*\*kwargs: Optional arguments that ``request`` takes. If
6 unmodified lines
113 kwargs.setdefault("allow_redirects", False)114 return request("head", url, **kwargs)115116103def post(url, data=None, json=None, **kwargs):117def post(118 url: _t.UriType,119 data: _t.DataType = None,120 json: _t.JsonType = None,121 **kwargs: Unpack[_t.PostKwargs],122) -> Response:123 r"""Sends a POST request.124125 :param url: URL for the new :class:`Request` object.126 :param data: (optional) Dictionary, list of tuples, bytes, or file-like
6 unmodified lines
133134 return request("post", url, data=data, json=json, **kwargs)135136118def put(url, data=None, **kwargs):137def put(138 url: _t.UriType, data: _t.DataType = None, **kwargs: Unpack[_t.DataKwargs]139) -> Response:140 r"""Sends a PUT request.141142 :param url: URL for the new :class:`Request` object.143 :param data: (optional) Dictionary, list of tuples, bytes, or file-like
6 unmodified lines
150151 return request("put", url, data=data, **kwargs)152153133def patch(url, data=None, **kwargs):154def patch(155 url: _t.UriType, data: _t.DataType = None, **kwargs: Unpack[_t.DataKwargs]156) -> Response:157 r"""Sends a PATCH request.158159 :param url: URL for the new :class:`Request` object.160 :param data: (optional) Dictionary, list of tuples, bytes, or file-like
6 unmodified lines
167168 return request("patch", url, data=data, **kwargs)169170148def delete(url, **kwargs):171def delete(url: _t.UriType, **kwargs: Unpack[_t.RequestKwargs]) -> Response:172 r"""Sends a DELETE request.173174 :param url: URL for the new :class:`Request` object.175 :param \*\*kwargs: Optional arguments that ``request`` takes.
5 unmodified lines
modified:src/requests/auth.py+75 added-35 removed
3 unmodified lines
45This module contains the authentication handlers for Requests.6"""78from __future__ import annotations910import hashlib11import os12import re13import threading14import time15import warnings16from base64 import b64encode17from typing import TYPE_CHECKING, Any, Final, cast, overload1819from ._internal_utils import to_native_string20from .compat import basestring, str, urlparse21from .cookies import extract_cookies_to_jar22from .utils import parse_dict_header2321CONTENT_TYPE_FORM_URLENCODED = "application/x-www-form-urlencoded"22CONTENT_TYPE_MULTI_PART = "multipart/form-data"24if TYPE_CHECKING:25 from http.cookiejar import CookieJar26 from typing import Any2728 from .models import PreparedRequest, Response2925def _basic_auth_str(username, password):30CONTENT_TYPE_FORM_URLENCODED: Final = "application/x-www-form-urlencoded"31CONTENT_TYPE_MULTI_PART: Final = "multipart/form-data"323334def _basic_auth_str(username: bytes | str, password: bytes | str) -> str:35 """Returns a Basic Auth string."""3637 # "I want us to put a big-ol' comment on top of it that38 # says that this behaviour is dumb but we need to preserve
1 unmodified line
40 # - Lukasa41 #42 # These are here solely to maintain backwards compatibility43 # for things like ints. This will be removed in 3.0.0.35 if not isinstance(username, basestring):44 if not isinstance(username, basestring): # type: ignore[reportUnnecessaryIsInstance] # runtime guard for non-str/bytes45 warnings.warn(46 "Non-string usernames will no longer be supported in Requests "47 f"3.0.0. Please convert the object you've passed in ({username!r}) to "48 "a string or bytes object in the near future to avoid "
1 unmodified line
50 category=DeprecationWarning,51 )52 username = str(username)5345 if not isinstance(password, basestring):54 if not isinstance(password, basestring): # type: ignore[reportUnnecessaryIsInstance] # runtime guard for non-str/bytes55 warnings.warn(56 "Non-string passwords will no longer be supported in Requests "57 f"3.0.0. Please convert the object you've passed in ({type(password)!r}) to "58 "a string or bytes object in the near future to avoid "
18 unmodified lines
7778class AuthBase:79 """Base class that all auth implementations derive from"""8072 def __call__(self, r):81 def __call__(self, r: PreparedRequest) -> PreparedRequest:82 raise NotImplementedError("Auth hooks must be callable.")838485class HTTPBasicAuth(AuthBase):86 """Attaches HTTP Basic Authentication to the given Request object."""8779 def __init__(self, username, password):88 username: bytes | str89 password: bytes | str9091 @overload92 def __init__(self, username: str, password: str) -> None: ...93 @overload94 def __init__(self, username: bytes, password: bytes) -> None: ...9596 def __init__(self, username: bytes | str, password: bytes | str) -> None:97 self.username = username98 self.password = password9983 def __eq__(self, other):100 def __eq__(self, other: object) -> bool:101 return all(102 [103 self.username == getattr(other, "username", None),104 self.password == getattr(other, "password", None),105 ]106 )10791 def __ne__(self, other):108 def __ne__(self, other: Any) -> bool:109 return not self == other11094 def __call__(self, r):111 def __call__(self, r: PreparedRequest) -> PreparedRequest:112 r.headers["Authorization"] = _basic_auth_str(self.username, self.password)113 return r114115116class HTTPProxyAuth(HTTPBasicAuth):117 """Attaches HTTP Proxy Authentication to a given Request object."""118102 def __call__(self, r):119 def __call__(self, r: PreparedRequest) -> PreparedRequest:120 r.headers["Proxy-Authorization"] = _basic_auth_str(self.username, self.password)121 return r122123124class HTTPDigestAuth(AuthBase):125 """Attaches HTTP Digest Authentication to the given Request object."""126110 def __init__(self, username, password):127 username: bytes | str128 password: bytes | str129 _thread_local: threading.local130 last_nonce: str131 nonce_count: int132 chal: dict[str, str]133 pos: int | None134 num_401_calls: int | None135136 @overload137 def __init__(self, username: str, password: str) -> None: ...138 @overload139 def __init__(self, username: bytes, password: bytes) -> None: ...140141 def __init__(self, username: bytes | str, password: bytes | str) -> None:142 self.username = username143 self.password = password144 # Keep state in per-thread local storage145 self._thread_local = threading.local()146116 def init_per_thread_state(self):147 def init_per_thread_state(self) -> None:148 # Ensure state is initialized just once per-thread149 if not hasattr(self._thread_local, "init"):150 self._thread_local.init = True151 self._thread_local.last_nonce = ""
1 unmodified line
153 self._thread_local.chal = {}154 self._thread_local.pos = None155 self._thread_local.num_401_calls = None156126 def build_digest_header(self, method, url):157 def build_digest_header(self, method: str, url: str) -> str | None:158 """159 :rtype: str160 """161
10 unmodified lines
172 _algorithm = algorithm.upper()173 # lambdas assume digest modules are imported at the top level174 if _algorithm == "MD5" or _algorithm == "MD5-SESS":175145 def md5_utf8(x):176 def md5_utf8(x: str | bytes) -> str:177 if isinstance(x, str):178 x = x.encode("utf-8")179 return hashlib.md5(x, usedforsecurity=False).hexdigest()180181 hash_utf8 = md5_utf8182 elif _algorithm == "SHA":183153 def sha_utf8(x):184 def sha_utf8(x: str | bytes) -> str:185 if isinstance(x, str):186 x = x.encode("utf-8")187 return hashlib.sha1(x, usedforsecurity=False).hexdigest()188189 hash_utf8 = sha_utf8190 elif _algorithm == "SHA-256":191161 def sha256_utf8(x):192 def sha256_utf8(x: str | bytes) -> str:193 if isinstance(x, str):194 x = x.encode("utf-8")195 return hashlib.sha256(x, usedforsecurity=False).hexdigest()196197 hash_utf8 = sha256_utf8198 elif _algorithm == "SHA-512":199169 def sha512_utf8(x):200 def sha512_utf8(x: str | bytes) -> str:201 if isinstance(x, str):202 x = x.encode("utf-8")203 return hashlib.sha512(x, usedforsecurity=False).hexdigest()204205 hash_utf8 = sha512_utf8206176 KD = lambda s, d: hash_utf8(f"{s}:{d}") # noqa:E731177207 if hash_utf8 is None:208 return None209210 def KD(s: str, d: str) -> str:211 return hash_utf8(f"{s}:{d}")212213 # XXX not implemented yet214 entdig = None215 p_parsed = urlparse(url)216 #: path is request-uri defined in RFC 2616 which should not be empty
18 unmodified lines
235 s += os.urandom(8)236237 cnonce = hashlib.sha1(s, usedforsecurity=False).hexdigest()[:16]238 if _algorithm == "MD5-SESS":207 HA1 = hash_utf8(f"{HA1}:{nonce}:{cnonce}")239 HA1 = hash_utf8(f"{HA1}:{nonce}:{cnonce}") # type: ignore[reportConstantRedefinition] # RFC 2617 terminology240241 if not qop:242 respdig = KD(HA1, f"{nonce}:{HA2}")243 elif qop == "auth" or "auth" in qop.split(","):
20 unmodified lines
264 base += f', qop="auth", nc={ncvalue}, cnonce="{cnonce}"'265266 return f"Digest {base}"267236 def handle_redirect(self, r, **kwargs):268 def handle_redirect(self, r: Response, **kwargs: Any) -> None:269 """Reset num_401_calls counter on redirects."""270 if r.is_redirect:271 self._thread_local.num_401_calls = 1272241 def handle_401(self, r, **kwargs):273 def handle_401(self, r: Response, **kwargs: Any) -> Response:274 """275 Takes the given response and tries digest-auth, if needed.276277 :rtype: requests.Response
7 unmodified lines
285286 if self._thread_local.pos is not None:287 # Rewind the file position indicator of the body to where288 # it was to resend the request.289 if (seek := getattr(r.request.body, "seek", None)) is not None:257 r.request.body.seek(self._thread_local.pos)290 seek(self._thread_local.pos)291 s_auth = r.headers.get("www-authenticate", "")292293 if "digest" in s_auth.lower() and self._thread_local.num_401_calls < 2:294 self._thread_local.num_401_calls += 1
4 unmodified lines
299 # to allow our new request to reuse the same one.300 r.content301 r.close()302 prep = r.request.copy()303 cookie_jar = cast("CookieJar", prep._cookies) # type: ignore[reportPrivateUsage]270 extract_cookies_to_jar(prep._cookies, r.request, r.raw)271 prep.prepare_cookies(prep._cookies)304 extract_cookies_to_jar(cookie_jar, r.request, r.raw)305 prep.prepare_cookies(cookie_jar)306273 prep.headers["Authorization"] = self.build_digest_header(274 prep.method, prep.url307 _digest_auth = self.build_digest_header(308 cast(str, prep.method), cast(str, prep.url)309 )310 if _digest_auth:311 prep.headers["Authorization"] = _digest_auth312 _r = r.connection.send(prep, **kwargs)313 _r.history.append(r)314 _r.request = prep315
1 unmodified line
317318 self._thread_local.num_401_calls = 1319 return r320285 def __call__(self, r):321 def __call__(self, r: PreparedRequest) -> PreparedRequest:322 # Initialize per-thread state, if needed323 self.init_per_thread_state()324 # If we have a saved nonce, skip the 401325 if self._thread_local.last_nonce:290 r.headers["Authorization"] = self.build_digest_header(r.method, r.url)291 try:292 self._thread_local.pos = r.body.tell()293 except AttributeError:326 _digest_auth = self.build_digest_header(327 cast(str, r.method), cast(str, r.url)328 )329 if _digest_auth:330 r.headers["Authorization"] = _digest_auth331 if (tell := getattr(r.body, "tell", None)) is not None:332 self._thread_local.pos = tell()333 else:334 # In the case of HTTPDigestAuth being reused and the body of335 # the previous request was a file-like object, pos has the336 # file position of the previous body. Ensure it's set to337 # None.
3 unmodified lines
341 self._thread_local.num_401_calls = 1342343 return r344305 def __eq__(self, other):345 def __eq__(self, other: object) -> bool:346 return all(347 [348 self.username == getattr(other, "username", None),349 self.password == getattr(other, "password", None),350 ]351 )352313 def __ne__(self, other):353 def __ne__(self, other: Any) -> bool:354 return not self == other
modified:src/requests/compat.py+12 added-5 removed
5 unmodified lines
6between Python 2 and Python 3. It remains for backwards7compatibility until the next major version.8"""910# pyright: reportUnusedImport=false1112from __future__ import annotations1314import importlib15import sys16from types import ModuleType1718# -------19# urllib320# -------16from urllib3 import __version__ as urllib3_version21from urllib3 import (22 __version__ as urllib3_version, # type: ignore[reportPrivateImportUsage]23)2425# Detect which major version of urllib3 is being used.26try:27 is_urllib3_1 = int(urllib3_version.split(".")[0]) == 1
5 unmodified lines
33# Character Detection34# -------------------353630def _resolve_char_detection():37def _resolve_char_detection() -> ModuleType | None:38 """Find supported character detection libraries."""39 chardet = None40 for lib in ("chardet", "charset_normalizer"):41 if chardet is None:
21 unmodified lines
6364# json/simplejson module import resolution65has_simplejson = False66try:60 import simplejson as json67 import simplejson as json # type: ignore[import-not-found]6869 has_simplejson = True70except ImportError:71 import json7273if has_simplejson:67 from simplejson import JSONDecodeError74 from simplejson import JSONDecodeError # type: ignore[import-not-found]75else:76 from json import JSONDecodeError7778# Keep OrderedDict for backwards compatibility.
22 unmodified lines
101 getproxies,102 getproxies_environment,103 parse_http_list,104 proxy_bypass,98 proxy_bypass_environment,105 proxy_bypass_environment, # type: ignore[attr-defined] # https://github.com/python/cpython/issues/145331106)107108builtin_str = str109str = str
4 unmodified lines
modified:src/requests/cookies.py+143 added-79 removed
5 unmodified lines
67requests.utils imports from here, so be careful with imports.8"""910from __future__ import annotations1112import calendar13import copy14import time15from collections.abc import Iterator, MutableMapping16from http.cookiejar import Cookie, CookieJar, CookiePolicy17from typing import TYPE_CHECKING, Any, TypeVar, overload1819from ._internal_utils import to_native_string20from ._types import is_prepared as _is_prepared15from .compat import Morsel, MutableMapping, cookielib, urlparse, urlunparse21from .compat import Morsel, cookielib, urlparse, urlunparse2217try:18 import threading19except ImportError:20 import dummy_threading as threading23if TYPE_CHECKING:24 from _typeshed import SupportsKeysAndGetItem2526 from .models import PreparedRequest2728import threading293031class MockRequest:24 """Wraps a `requests.Request` to mimic a `urllib2.Request`.32 """Wraps a `requests.PreparedRequest` to mimic a `urllib2.Request`.3334 The code in `http.cookiejar.CookieJar` expects this interface in order to correctly35 manage cookie policies, i.e., determine whether a cookie can be set, given the36 domains of the request and the cookie.
2 unmodified lines
39 the new headers via `get_new_headers()` and interpreting them appropriately. You40 probably want `get_cookie_header`, defined below.41 """4243 type: str4435 def __init__(self, request):45 def __init__(self, request: PreparedRequest) -> None:46 assert _is_prepared(request)47 self._r = request37 self._new_headers = {}48 self._new_headers: dict[str, str] = {}49 self.type = urlparse(self._r.url).scheme5040 def get_type(self):51 def get_type(self) -> str:52 return self.type5343 def get_host(self):54 def get_host(self) -> str:55 return urlparse(self._r.url).netloc5646 def get_origin_req_host(self):57 def get_origin_req_host(self) -> str:58 return self.get_host()5949 def get_full_url(self):60 def get_full_url(self) -> str:61 # Only return the response's URL if the user hadn't set the Host62 # header63 if not self._r.headers.get("Host"):64 return self._r.url
11 unmodified lines
76 parsed.fragment,77 ]78 )7969 def is_unverifiable(self):80 def is_unverifiable(self) -> bool:81 return True8272 def has_header(self, name):83 def has_header(self, name: str) -> bool:84 return name in self._r.headers or name in self._new_headers8575 def get_header(self, name, default=None):76 return self._r.headers.get(name, self._new_headers.get(name, default))86 def get_header(self, name: str, default: str | None = None) -> str | None:87 return self._r.headers.get(name, self._new_headers.get(name, default)) # type: ignore[return-value]8878 def add_header(self, key, val):89 def add_header(self, key: str, val: str) -> None:90 """cookiejar has no legitimate use for this method; add it back if you find one."""91 raise NotImplementedError(92 "Cookie headers should be added with add_unredirected_header()"93 )9484 def add_unredirected_header(self, name, value):95 def add_unredirected_header(self, name: str, value: str) -> None:96 self._new_headers[name] = value9787 def get_new_headers(self):98 def get_new_headers(self) -> dict[str, str]:99 return self._new_headers100101 @property91 def unverifiable(self):102 def unverifiable(self) -> bool:103 return self.is_unverifiable()104105 @property95 def origin_req_host(self):106 def origin_req_host(self) -> str:107 return self.get_origin_req_host()108109 @property99 def host(self):110 def host(self) -> str:111 return self.get_host()112113114class MockResponse:
2 unmodified lines
117 ...what? Basically, expose the parsed HTTP headers from the server response118 the way `http.cookiejar` expects to see them.119 """120110 def __init__(self, headers):121 def __init__(self, headers: Any) -> None:122 """Make a MockResponse for `cookiejar` to read.123124 :param headers: a httplib.HTTPMessage or analogous carrying the headers125 """126 self._headers = headers127117 def info(self):128 def info(self) -> Any:129 return self._headers130120 def getheaders(self, name):131 def getheaders(self, name: str) -> Any:132 self._headers.getheaders(name)133134124def extract_cookies_to_jar(jar, request, response):135def extract_cookies_to_jar(136 jar: CookieJar, request: PreparedRequest, response: Any137) -> None:138 """Extract the cookies from the response into a CookieJar.139140 :param jar: http.cookiejar.CookieJar (not necessarily a RequestsCookieJar)141 :param request: our own requests.Request object
4 unmodified lines
146 # the _original_response field is the wrapped httplib.HTTPResponse object,147 req = MockRequest(request)148 # pull out the HTTPMessage with the headers and put it in the mock:149 res = MockResponse(response._original_response.msg)137 jar.extract_cookies(res, req)150 jar.extract_cookies(res, req) # type: ignore[arg-type]151152140def get_cookie_header(jar, request):153def get_cookie_header(jar: CookieJar, request: PreparedRequest) -> str | None:154 """155 Produce an appropriate Cookie header string to be sent with `request`, or None.156157 :rtype: str158 """159 r = MockRequest(request)147 jar.add_cookie_header(r)160 jar.add_cookie_header(r) # type: ignore[arg-type]161 return r.get_new_headers().get("Cookie")162163151def remove_cookie_by_name(cookiejar, name, domain=None, path=None):164def remove_cookie_by_name(165 cookiejar: CookieJar, name: str, domain: str | None = None, path: str | None = None166) -> None:167 """Unsets a cookie by name, by default over all domains and paths.168169 Wraps CookieJar.clear(), is O(n).170 """156 clearables = []171 clearables: list[tuple[str, str, str]] = []172 for cookie in cookiejar:173 if cookie.name != name:174 continue175 if domain is not None and domain != cookie.domain:
11 unmodified lines
187 Use .get and .set and include domain and path args in order to be more specific.188 """189190176class RequestsCookieJar(cookielib.CookieJar, MutableMapping):191class RequestsCookieJar(CookieJar, MutableMapping[str, str | None]): # type: ignore[misc]192 """Compatibility class; is a http.cookiejar.CookieJar, but exposes a dict193 interface.194195 This is the CookieJar we create by default for requests and sessions that
9 unmodified lines
205206 .. warning:: dictionary operations that are normally O(1) may be O(n).207 """208194 def get(self, name, default=None, domain=None, path=None):209 _policy: CookiePolicy210211 def get( # type: ignore[override]212 self,213 name: str,214 default: str | None = None,215 domain: str | None = None,216 path: str | None = None,217 ) -> str | None:218 """Dict-like get() that also supports optional domain and path args in219 order to resolve naming collisions from using one cookie jar over220 multiple domains.221
3 unmodified lines
225 return self._find_no_duplicates(name, domain, path)226 except KeyError:227 return default228206 def set(self, name, value, **kwargs):229 def set(230 self, name: str, value: str | Morsel[dict[str, str]] | None, **kwargs: Any231 ) -> Cookie | None:232 """Dict-like set() that also supports optional domain and path args in233 order to resolve naming collisions from using one cookie jar over234 multiple domains.235 """
10 unmodified lines
246 c = create_cookie(name, value, **kwargs)247 self.set_cookie(c)248 return c249225 def iterkeys(self):250 def iterkeys(self) -> Iterator[str]:251 """Dict-like iterkeys() that returns an iterator of names of cookies252 from the jar.253254 .. seealso:: itervalues() and iteritems().255 """256 for cookie in iter(self):257 yield cookie.name258234 def keys(self):259 def keys(self) -> list[str]: # type: ignore[override]260 """Dict-like keys() that returns a list of names of cookies from the261 jar.262263 .. seealso:: values() and items().264 """265 return list(self.iterkeys())266242 def itervalues(self):267 def itervalues(self) -> Iterator[str | None]:268 """Dict-like itervalues() that returns an iterator of values of cookies269 from the jar.270271 .. seealso:: iterkeys() and iteritems().272 """273 for cookie in iter(self):274 yield cookie.value275251 def values(self):276 def values(self) -> list[str | None]: # type: ignore[override]277 """Dict-like values() that returns a list of values of cookies from the278 jar.279280 .. seealso:: keys() and items().281 """282 return list(self.itervalues())283259 def iteritems(self):284 def iteritems(self) -> Iterator[tuple[str, str | None]]:285 """Dict-like iteritems() that returns an iterator of name-value tuples286 from the jar.287288 .. seealso:: iterkeys() and itervalues().289 """290 for cookie in iter(self):291 yield cookie.name, cookie.value292268 def items(self):293 def items(self) -> list[tuple[str, str | None]]: # type: ignore[override]294 """Dict-like items() that returns a list of name-value tuples from the295 jar. Allows client-code to call ``dict(RequestsCookieJar)`` and get a296 vanilla python dict of key value pairs.297298 .. seealso:: keys() and values().299 """300 return list(self.iteritems())301277 def list_domains(self):302 def list_domains(self) -> list[str]:303 """Utility method to list all the domains in the jar."""279 domains = []304 domains: list[str] = []305 for cookie in iter(self):306 if cookie.domain not in domains:307 domains.append(cookie.domain)308 return domains309285 def list_paths(self):310 def list_paths(self) -> list[str]:311 """Utility method to list all the paths in the jar."""287 paths = []312 paths: list[str] = []313 for cookie in iter(self):314 if cookie.path not in paths:315 paths.append(cookie.path)316 return paths317293 def multiple_domains(self):318 def multiple_domains(self) -> bool:319 """Returns True if there are multiple domains in the jar.320 Returns False otherwise.321322 :rtype: bool323 """299 domains = []324 domains: list[str] = []325 for cookie in iter(self):301 if cookie.domain is not None and cookie.domain in domains:326 if cookie.domain is not None and cookie.domain in domains: # type: ignore[reportUnnecessaryComparison] # defensive check327 return True328 domains.append(cookie.domain)329 return False # there is only one domain in jar330306 def get_dict(self, domain=None, path=None):331 def get_dict(332 self, domain: str | None = None, path: str | None = None333 ) -> dict[str, str | None]:334 """Takes as an argument an optional domain and path and returns a plain335 old Python dict of name-value pairs of cookies that meet the336 requirements.337338 :rtype: dict339 """313 dictionary = {}340 dictionary: dict[str, str | None] = {}341 for cookie in iter(self):342 if (domain is None or cookie.domain == domain) and (343 path is None or cookie.path == path344 ):345 dictionary[cookie.name] = cookie.value346 return dictionary347348 def __iter__(self) -> Iterator[Cookie]: # type: ignore[override]349 """RequestCookieJar's __iter__ comes from CookieJar not MutableMapping."""350 return super().__iter__()351321 def __contains__(self, name):352 def __contains__(self, name: object) -> bool:353 try:354 return super().__contains__(name)355 except CookieConflictError:356 return True357327 def __getitem__(self, name):358 def __getitem__(self, name: str) -> str | None:359 """Dict-like __getitem__() for compatibility with client code. Throws360 exception if there are more than one cookie with name. In that case,361 use the more explicit get() method instead.362363 .. warning:: operation is O(n), not O(1).364 """365 return self._find_no_duplicates(name)366336 def __setitem__(self, name, value):367 def __setitem__(368 self, name: str, value: str | Morsel[dict[str, str]] | None369 ) -> None:370 """Dict-like __setitem__ for compatibility with client code. Throws371 exception if there is already a cookie of that name in the jar. In that372 case, use the more explicit set() method instead.373 """374 self.set(name, value)375343 def __delitem__(self, name):376 def __delitem__(self, name: str) -> None:377 """Deletes a cookie given a name. Wraps ``http.cookiejar.CookieJar``'s378 ``remove_cookie_by_name()``.379 """380 remove_cookie_by_name(self, name)381349 def set_cookie(self, cookie, *args, **kwargs):382 def set_cookie(self, cookie: Cookie, *args: Any, **kwargs: Any) -> None:383 if (351 hasattr(cookie.value, "startswith")352 and cookie.value.startswith('"')353 and cookie.value.endswith('"')384 (value := cookie.value) is not None385 and value.startswith('"')386 and value.endswith('"')387 ):355 cookie.value = cookie.value.replace('\\"', "")388 cookie.value = value.replace('\\"', "")389 return super().set_cookie(cookie, *args, **kwargs)390358 def update(self, other):391 def update( # type: ignore[override]392 self, other: CookieJar | SupportsKeysAndGetItem[str, str]393 ) -> None:394 """Updates this jar with cookies from another CookieJar or dict-like"""395 if isinstance(other, cookielib.CookieJar):396 for cookie in other:397 self.set_cookie(copy.copy(cookie))398 else:399 super().update(other)400366 def _find(self, name, domain=None, path=None):401 def _find(402 self, name: str, domain: str | None = None, path: str | None = None403 ) -> str | None:404 """Requests uses this method internally to get cookie values.405406 If there are conflicting cookies, _find arbitrarily chooses one.407 See _find_no_duplicates if you want an exception thrown if there are
11 unmodified lines
419 return cookie.value420421 raise KeyError(f"name={name!r}, domain={domain!r}, path={path!r}")422386 def _find_no_duplicates(self, name, domain=None, path=None):423 def _find_no_duplicates(424 self, name: str, domain: str | None = None, path: str | None = None425 ) -> str:426 """Both ``__get_item__`` and ``get`` call this function: it's never427 used elsewhere in Requests.428429 :param name: a string containing name of cookie
16 unmodified lines
446 )447 # we will eventually return this as long as no cookie conflict448 toReturn = cookie.value449411 if toReturn:450 if toReturn is not None:451 return toReturn452 raise KeyError(f"name={name!r}, domain={domain!r}, path={path!r}")453415 def __getstate__(self):454 def __getstate__(self) -> dict[str, Any]:455 """Unlike a normal CookieJar, this class is pickleable."""456 state = self.__dict__.copy()457 # remove the unpickleable RLock object458 state.pop("_cookies_lock")459 return state460422 def __setstate__(self, state):461 def __setstate__(self, state: dict[str, Any]) -> None:462 """Unlike a normal CookieJar, this class is pickleable."""463 self.__dict__.update(state)464 if "_cookies_lock" not in self.__dict__:465 self._cookies_lock = threading.RLock()466428 def copy(self):467 def copy(self) -> RequestsCookieJar:468 """Return a copy of this RequestsCookieJar."""469 new_cj = RequestsCookieJar()470 new_cj.set_policy(self.get_policy())471 new_cj.update(self)472 return new_cj473435 def get_policy(self):474 def get_policy(self) -> CookiePolicy:475 """Return the CookiePolicy instance used."""476 return self._policy477478440def _copy_cookie_jar(jar):479def _copy_cookie_jar(jar: CookieJar | None) -> CookieJar | None: # type: ignore[reportUnusedFunction] # cross-module usage in models.py480 if jar is None:481 return None482444 if hasattr(jar, "copy"):483 if copy_method := getattr(jar, "copy", None):484 # We're dealing with an instance of RequestsCookieJar446 return jar.copy()485 return copy_method()486 # We're dealing with a generic CookieJar instance487 new_jar = copy.copy(jar)488 new_jar.clear()489 for cookie in jar:490 new_jar.set_cookie(copy.copy(cookie))491 return new_jar492493455def create_cookie(name, value, **kwargs):494def create_cookie(name: str, value: str, **kwargs: Any) -> Cookie:495 """Make a cookie from underspecified parameters.496497 By default, the pair of `name` and `value` will be set for the domain ''498 and sent on every request (this is sometimes called a "supercookie").499 """461 result = {500 result: dict[str, Any] = {501 "version": 0,502 "name": name,503 "value": value,504 "port": None,
22 unmodified lines
527528 return cookielib.Cookie(**result)529530492def morsel_to_cookie(morsel):531def morsel_to_cookie(morsel: Morsel[Any]) -> Cookie:532 """Convert a Morsel object into a Cookie containing the one k/v pair."""533495 expires = None534 expires: int | None = None535 if morsel["max-age"]:536 try:537 expires = int(time.time() + int(morsel["max-age"]))538 except ValueError:
17 unmodified lines
556 version=morsel["version"] or 0,557 )558559521def cookiejar_from_dict(cookie_dict, cookiejar=None, overwrite=True):560_CookieJarT = TypeVar("_CookieJarT", bound=CookieJar)561562563@overload564def cookiejar_from_dict(565 cookie_dict: dict[str, str] | None,566 cookiejar: None = None,567 overwrite: bool = True,568) -> RequestsCookieJar: ...569570571@overload572def cookiejar_from_dict(573 cookie_dict: dict[str, str] | None,574 cookiejar: _CookieJarT,575 overwrite: bool = True,576) -> _CookieJarT: ...577578579def cookiejar_from_dict(580 cookie_dict: dict[str, str] | None,581 cookiejar: CookieJar | None = None,582 overwrite: bool = True,583) -> CookieJar:584 """Returns a CookieJar from a key/value dictionary.585586 :param cookie_dict: Dict of key/values to insert into CookieJar.587 :param cookiejar: (optional) A cookiejar to add the cookies to.
12 unmodified lines
600601 return cookiejar602603542def merge_cookies(cookiejar, cookies):604def merge_cookies(605 cookiejar: CookieJar, cookies: dict[str, str] | CookieJar | None606) -> CookieJar:607 """Add cookies to cookiejar and returns a merged CookieJar.608609 :param cookiejar: CookieJar object to add the cookies to.610 :param cookies: Dictionary or CookieJar object to be added.611 :rtype: CookieJar612 """549 if not isinstance(cookiejar, cookielib.CookieJar):613 if not isinstance(cookiejar, cookielib.CookieJar): # type: ignore[reportUnnecessaryIsInstance] # runtime guard614 raise ValueError("You can only merge into CookieJar")615616 if isinstance(cookies, dict):617 cookiejar = cookiejar_from_dict(cookies, cookiejar=cookiejar, overwrite=False)618 elif isinstance(cookies, cookielib.CookieJar):555 try:556 cookiejar.update(cookies)557 except AttributeError:619 if update_method := getattr(cookiejar, "update", None):620 update_method(cookies)621 else:622 for cookie_in_jar in cookies:623 cookiejar.set_cookie(cookie_in_jar)624625 return cookiejar
modified:src/requests/exceptions.py+15 added-5 removed
3 unmodified lines
45This module contains the set of Requests' exceptions.6"""78from __future__ import annotations910from typing import TYPE_CHECKING, Any1112from urllib3.exceptions import HTTPError as BaseHTTPError1314from .compat import JSONDecodeError as CompatJSONDecodeError1516if TYPE_CHECKING:17 from .models import PreparedRequest, Request, Response181920class RequestException(IOError):21 """There was an ambiguous exception that occurred while handling your22 request.23 """2418 def __init__(self, *args, **kwargs):25 response: Response | None26 request: Request | PreparedRequest | None2728 def __init__(self, *args: Any, **kwargs: Any) -> None:29 """Initialize RequestException with `request` and `response` objects."""20 response = kwargs.pop("response", None)30 response: Response | None = kwargs.pop("response", None)31 self.response = response32 self.request = kwargs.pop("request", None)33 if response is not None and not self.request and hasattr(response, "request"):24 self.request = self.response.request34 self.request = response.request35 super().__init__(*args, **kwargs)363738class InvalidJSONError(RequestException):
2 unmodified lines
4142class JSONDecodeError(InvalidJSONError, CompatJSONDecodeError):43 """Couldn't decode the text into json"""4435 def __init__(self, *args, **kwargs):45 def __init__(self, *args: Any, **kwargs: Any) -> None:46 """47 Construct the JSONDecodeError instance first with all48 args. Then use it's args to construct the IOError so that49 the json specific args aren't used as IOError specific args
1 unmodified line
51 """52 CompatJSONDecodeError.__init__(self, *args)53 InvalidJSONError.__init__(self, *self.args, **kwargs)5445 def __reduce__(self):55 def __reduce__(self) -> tuple[Any, ...] | str:56 """57 The __reduce__ method called when pickling the object must58 be the one from the JSONDecodeError (be it json/simplejson)59 as it expects all the arguments for instantiation, not just
103 unmodified lines
modified:src/requests/help.py+14 added-11 removed
1"""Module containing bug report helper(s)."""23# pyright: reportUnknownMemberType=false45import json6import platform7import ssl8import sys9from typing import Any1011import idna12import urllib313
4 unmodified lines
18except ImportError:19 charset_normalizer = None2021try:19 import chardet22 import chardet # type: ignore[import-not-found]23except ImportError:24 chardet = None2526try:
2 unmodified lines
29 pyopenssl = None30 OpenSSL = None31 cryptography = None32else:30 import cryptography31 import OpenSSL33 import cryptography # type: ignore[import-not-found]34 import OpenSSL # type: ignore[import-not-found]353637def _implementation():38 """Return a dict with the Python implementation and version.
10 unmodified lines
4950 if implementation == "CPython":51 implementation_version = platform.python_version()52 elif implementation == "PyPy":50 pypy = sys.pypy_version_info53 pypy = sys.pypy_version_info # type: ignore[attr-defined]54 implementation_version = f"{pypy.major}.{pypy.minor}.{pypy.micro}"52 if sys.pypy_version_info.releaselevel != "final":55 if sys.pypy_version_info.releaselevel != "final": # type: ignore[attr-defined]56 implementation_version = "".join(54 [implementation_version, sys.pypy_version_info.releaselevel]57 [implementation_version, sys.pypy_version_info.releaselevel] # type: ignore[attr-defined]58 )59 elif implementation == "Jython":60 implementation_version = platform.python_version() # Complete Guess61 elif implementation == "IronPython":
3 unmodified lines
6566 return {"name": implementation, "version": implementation_version}676866def info():69def info() -> dict[str, Any]:70 """Generate information for a bug report."""71 try:72 platform_info = {73 "system": platform.system(),
5 unmodified lines
79 "release": "Unknown",80 }8182 implementation_info = _implementation()80 urllib3_info = {"version": urllib3.__version__}83 urllib3_info = {"version": urllib3.__version__} # type: ignore[reportPrivateImportUsage]84 charset_normalizer_info = {"version": None}82 chardet_info = {"version": None}85 chardet_info: dict[str, str | None] = {"version": None}86 if charset_normalizer:87 charset_normalizer_info = {"version": charset_normalizer.__version__}88 if chardet:89 chardet_info = {"version": chardet.__version__}9088 pyopenssl_info = {91 pyopenssl_info: dict[str, str | None] = {92 "version": None,93 "openssl_version": "",94 }95 if OpenSSL:
8 unmodified lines
104 "version": getattr(idna, "__version__", ""),105 }106107 system_ssl = ssl.OPENSSL_VERSION_NUMBER105 system_ssl_info = {"version": f"{system_ssl:x}" if system_ssl is not None else ""}108 system_ssl_info = {"version": f"{system_ssl:x}" if system_ssl is not None else ""} # type: ignore[reportUnnecessaryComparison]109110 return {111 "platform": platform_info,112 "implementation": implementation_info,
22 unmodified lines
modified:src/requests/hooks.py+23 added-9 removed
8 unmodified lines
9``response``:10 The response generated from a Request.11"""1213HOOKS = ["response"]13from __future__ import annotations1415from collections.abc import Callable, Iterable16from typing import TYPE_CHECKING, Any1716def default_hooks():18if TYPE_CHECKING:19 from . import _types as _t20 from .models import Response2122HOOKS: list[str] = ["response"]232425def default_hooks() -> dict[str, list[_t.HookType]]:26 return {event: [] for event in HOOKS}272829# TODO: response is the only one303123def dispatch_hook(key, hooks, hook_data, **kwargs):32def dispatch_hook(33 key: str,34 hooks: _t.HooksInputType | None,35 hook_data: Response,36 **kwargs: Any,37) -> Response:38 """Dispatches a hook dictionary on a given piece of data."""25 hooks = hooks or {}26 hooks = hooks.get(key)27 if hooks:28 if hasattr(hooks, "__call__"):29 hooks = [hooks]30 for hook in hooks:39 hooks_dict = hooks or {}40 hook_list: Iterable[_t.HookType] | _t.HookType | None = hooks_dict.get(key)41 if hook_list:42 if isinstance(hook_list, Callable):43 hook_list = [hook_list]44 for hook in hook_list:45 _hook_data = hook(hook_data, **kwargs)46 if _hook_data is not None:47 hook_data = _hook_data48 return hook_data
modified:src/requests/models.py+257 added-123 removed
3 unmodified lines
45This module contains the primary objects that power Requests.6"""78from __future__ import annotations910import datetime1112# Import encoding now, to avoid implicit import later.13# Implicit import within threads may cause LookupError when standard library is in a ZIP,14# such as in Embedded Python. See https://github.com/psf/requests/issues/3578.13import encodings.idna # noqa: F40115import encodings.idna # noqa: F401 # type: ignore[reportUnusedImport]16from collections.abc import Callable, Generator, Iterable, Iterator, Mapping17from io import UnsupportedOperation18from typing import (19 TYPE_CHECKING,20 Any,21 Final,22 Literal,23 cast,24 overload,25)2627from urllib3.exceptions import (28 DecodeError,29 LocationParseError,
5 unmodified lines
35from urllib3.filepost import encode_multipart_formdata36from urllib3.util import parse_url3738from ._internal_utils import to_native_string, unicode_is_ascii39from ._types import SupportsRead as _SupportsRead40from .auth import HTTPBasicAuth41from .compat import (30 Callable,42 JSONDecodeError,32 Mapping,43 basestring,44 builtin_str,45 chardet,46 cookielib,
1 unmodified line
48 urlsplit,49 urlunparse,50)51from .compat import json as complexjson42from .cookies import _copy_cookie_jar, cookiejar_from_dict, get_cookie_header52from .cookies import (53 _copy_cookie_jar, # type: ignore[reportPrivateUsage]54 cookiejar_from_dict,55 get_cookie_header,56)57from .exceptions import (58 ChunkedEncodingError,59 ConnectionError,60 ContentDecodingError,
20 unmodified lines
81 super_len,82 to_key_val_list,83)8485if TYPE_CHECKING:86 from http.cookiejar import CookieJar8788 from typing_extensions import Self8990 from . import _types as _t91 from .adapters import HTTPAdapter92 from .cookies import RequestsCookieJar9394#: The set of HTTP status codes that indicate an automatically95#: processable redirect.73REDIRECT_STATI = (96REDIRECT_STATI: Final[tuple[int, ...]] = ( # type: ignore[assignment]97 codes.moved, # 30198 codes.found, # 30299 codes.other, # 303100 codes.temporary_redirect, # 307101 codes.permanent_redirect, # 308102)10381DEFAULT_REDIRECT_LIMIT = 3082CONTENT_CHUNK_SIZE = 10 * 102483ITER_CHUNK_SIZE = 512104DEFAULT_REDIRECT_LIMIT: int = 30105CONTENT_CHUNK_SIZE: int = 10 * 1024106ITER_CHUNK_SIZE: int = 512107108109class RequestEncodingMixin:110 url: str | None111112 @property88 def path_url(self):113 def path_url(self) -> str:114 """Build the path URL to use."""11591 url = []116 url: list[str] = []11793 p = urlsplit(self.url)118 p = urlsplit(cast(str, self.url))119120 path = p.path121 if not path:122 path = "/"
6 unmodified lines
129 url.append(query)130131 return "".join(url)132133 @overload134 @staticmethod109 def _encode_params(data):135 def _encode_params(data: str) -> str: ...136137 @overload138 @staticmethod139 def _encode_params(data: bytes) -> bytes: ...140141 @overload142 @staticmethod143 def _encode_params(144 data: _t.SupportsRead[str | bytes],145 ) -> _t.SupportsRead[str | bytes]: ...146147 @overload148 @staticmethod149 def _encode_params(data: _t.KVDataType) -> str: ...150151 @staticmethod152 def _encode_params(153 data: _t.EncodableDataType,154 ) -> str | bytes | _t.SupportsRead[str | bytes]:155 """Encode parameters in a piece of data.156157 Will successfully encode parameters when passed as a dict or a list of158 2-tuples. Order is retained if data is a list of 2-tuples but arbitrary
1 unmodified line
160 """161162 if isinstance(data, (str, bytes)):163 return data119 elif hasattr(data, "read"):164 elif isinstance(data, _SupportsRead):165 return data166 elif hasattr(data, "__iter__"):122 result = []167 result: list[tuple[bytes, bytes]] = []168 for k, vs in to_key_val_list(data):169 if isinstance(vs, basestring) or not hasattr(vs, "__iter__"):170 vs = [vs]171 for v in vs:
5 unmodified lines
177 )178 )179 return urlencode(result, doseq=True)180 else:136 return data181 return data # type: ignore[return-value] # unreachable for valid _t.DataType182183 @staticmethod139 def _encode_files(files, data):184 def _encode_files(185 files: _t.FilesType, data: _t.RawDataType | None186 ) -> tuple[bytes, str]:187 """Build the body for a multipart/form-data request.188189 Will successfully encode files when passed as a dict or a list of190 tuples. Order is retained if data is a list of tuples but arbitrary
5 unmodified lines
196 raise ValueError("Files must be provided.")197 elif isinstance(data, basestring):198 raise ValueError("Data must not be a string.")199153 new_fields = []200 new_fields: list[RequestField | tuple[str, bytes]] = []201 fields = to_key_val_list(data or {})202 files = to_key_val_list(files or {})203204 for field, val in fields:
30 unmodified lines
235 fp = v236237 if isinstance(fp, (str, bytes, bytearray)):238 fdata = fp192 elif hasattr(fp, "read"):239 elif isinstance(fp, _SupportsRead): # type: ignore[reportUnnecessaryIsInstance] # defensive check for untyped callers240 fdata = fp.read()194 elif fp is None:241 elif fp is None: # type: ignore[reportUnnecessaryComparison] # defensive check for untyped callers242 continue243 else:244 fdata = fp245
6 unmodified lines
252 return body, content_type253254255class RequestHooksMixin:209 def register_hook(self, event, hook):256 hooks: dict[str, list[_t.HookType]]257258 def register_hook(259 self, event: str, hook: Iterable[_t.HookType] | _t.HookType260 ) -> None:261 """Properly register a hook."""262263 if event not in self.hooks:264 raise ValueError(f'Unsupported event specified, with event name "{event}"')265266 if isinstance(hook, Callable):267 self.hooks[event].append(hook)268 elif hasattr(hook, "__iter__"):218 self.hooks[event].extend(h for h in hook if isinstance(h, Callable))269 self.hooks[event].extend(h for h in hook if isinstance(h, Callable)) # type: ignore[reportUnnecessaryIsInstance] # defensive runtime filter270220 def deregister_hook(self, event, hook):271 def deregister_hook(self, event: str, hook: _t.HookType) -> bool:272 """Deregister a previously registered hook.273 Returns True if the hook existed, False if not.274 """275
31 unmodified lines
307 >>> req.prepare()308 <PreparedRequest [GET]>309 """310311 method: str | None312 url: _t.UriType | None313 headers: CaseInsensitiveDict[str] | Mapping[str, str | bytes] | None314 files: _t.FilesType315 data: _t.DataType316 json: _t.JsonType317 params: _t.ParamsType318 auth: _t.AuthType319 cookies: RequestsCookieJar | CookieJar | dict[str, str] | None320321 def __init__(322 self,262 method=None,263 url=None,264 headers=None,265 files=None,266 data=None,267 params=None,268 auth=None,269 cookies=None,270 hooks=None,271 json=None,272 ):323 method: str | None = None,324 url: _t.UriType | None = None,325 headers: Mapping[str, str | bytes] | None = None,326 files: _t.FilesType = None,327 data: _t.DataType = None,328 params: _t.ParamsType = None,329 auth: _t.AuthType = None,330 cookies: RequestsCookieJar | CookieJar | dict[str, str] | None = None,331 hooks: _t.HooksInputType | None = None,332 json: _t.JsonType = None,333 ) -> None:334 # Default empty dicts for dict params.335 data = [] if data is None else data336 files = [] if files is None else files337 headers = {} if headers is None else headers
13 unmodified lines
351 self.params = params352 self.auth = auth353 self.cookies = cookies354294 def __repr__(self):355 def __repr__(self) -> str:356 return f"<Request [{self.method}]>"357297 def prepare(self):358 def prepare(self) -> PreparedRequest:359 """Constructs a :class:`PreparedRequest <PreparedRequest>` for transmission and returns it."""360 p = PreparedRequest()361 p.prepare(362 method=self.method,
30 unmodified lines
393 >>> s.send(r)394 <Response [200]>395 """396397 method: str | None398 url: str | None399 headers: CaseInsensitiveDict[str | bytes]400 _cookies: RequestsCookieJar | CookieJar | None401 body: _t.BodyType402 hooks: dict[str, list[_t.HookType]]403 _body_position: int | object | None404336 def __init__(self):405 def __init__(self) -> None:406 #: HTTP verb to send to the server.407 self.method = None408 #: HTTP URL to send the request to.409 self.url = None410 #: dictionary of HTTP headers.342 self.headers = None411 self.headers = None # type: ignore[assignment]412 # The `CookieJar` used to create the Cookie header will be stored here413 # after prepare_cookies is called414 self._cookies = None415 #: request body to send to the server.
4 unmodified lines
420 self._body_position = None421422 def prepare(423 self,355 method=None,356 url=None,357 headers=None,358 files=None,359 data=None,360 params=None,361 auth=None,362 cookies=None,363 hooks=None,364 json=None,365 ):424 method: str | None = None,425 url: _t.UriType | None = None,426 headers: Mapping[str, str | bytes] | None = None,427 files: _t.FilesType = None,428 data: _t.DataType = None,429 params: _t.ParamsType = None,430 auth: _t.AuthType = None,431 cookies: RequestsCookieJar | CookieJar | dict[str, str] | None = None,432 hooks: _t.HooksInputType | None = None,433 json: _t.JsonType = None,434 ) -> None:435 """Prepares the entire request with the given parameters."""436437 url = cast("_t.UriType", url)438 self.prepare_method(method)439 self.prepare_url(url, params)440 self.prepare_headers(headers)441 self.prepare_cookies(cookies)
5 unmodified lines
447448 # This MUST go after prepare_auth. Authenticators could add a hook449 self.prepare_hooks(hooks)450381 def __repr__(self):451 def __repr__(self) -> str:452 return f"<PreparedRequest [{self.method}]>"453384 def copy(self):454 def copy(self) -> PreparedRequest:455 p = PreparedRequest()456 p.method = self.method457 p.url = self.url388 p.headers = self.headers.copy() if self.headers is not None else None458 p.headers = self.headers.copy() if self.headers is not None else None # type: ignore[assignment]459 p._cookies = _copy_cookie_jar(self._cookies)460 p.body = self.body461 p.hooks = self.hooks462 p._body_position = self._body_position463 return p464395 def prepare_method(self, method):465 def prepare_method(self, method: str | None) -> None:466 """Prepares the given HTTP method."""467 self.method = method468 if self.method is not None:469 self.method = to_native_string(self.method.upper())470471 @staticmethod402 def _get_idna_encoded_host(host):472 def _get_idna_encoded_host(host: str) -> str:473 import idna474475 try:476 host = idna.encode(host, uts46=True).decode("utf-8")477 except idna.IDNAError:478 raise UnicodeError479 return host480411 def prepare_url(self, url, params):481 def prepare_url(482 self,483 url: _t.UriType,484 params: _t.ParamsType,485 ) -> None:486 """Prepares the given HTTP URL."""487 #: Accept objects that have string representations.488 #: We're unable to blindly call unicode/str functions489 #: as this will include the bytestring indicator (b'')
55 unmodified lines
545546 if isinstance(params, (str, bytes)):547 params = to_native_string(params)548549 if params is not None:475 enc_params = self._encode_params(params)550 enc_params = self._encode_params(params)551 else:552 enc_params = ""553554 if enc_params:555 if query:556 query = f"{query}&{enc_params}"557 else:558 query = enc_params559482 url = requote_uri(urlunparse([scheme, netloc, path, None, query, fragment]))560 url = requote_uri(urlunparse((scheme, netloc, path, "", query, fragment)))561 self.url = url562485 def prepare_headers(self, headers):563 def prepare_headers(self, headers: Mapping[str, str | bytes] | None) -> None:564 """Prepares the given HTTP headers."""565566 self.headers = CaseInsensitiveDict()567 if headers:
2 unmodified lines
570 check_header_validity(header)571 name, value = header572 self.headers[to_native_string(name)] = value573496 def prepare_body(self, data, files, json=None):574 def prepare_body(575 self, data: _t.DataType, files: _t.FilesType, json: _t.JsonType = None576 ) -> None:577 """Prepares the given HTTP body data."""578579 # Check if file, fo, generator, iterator.580 # If not, run through normal process.
14 unmodified lines
595596 if not isinstance(body, bytes):597 body = body.encode("utf-8")598519 is_stream = all(520 [521 hasattr(data, "__iter__"),522 not isinstance(data, (basestring, list, tuple, Mapping)),523 ]524 )525526 if is_stream:599 if isinstance(data, Iterable) and not isinstance(600 data, (str, bytes, list, tuple, Mapping)601 ):602 try:603 length = super_len(data)604 except (TypeError, AttributeError, UnsupportedOperation):605 length = None
4 unmodified lines
610 # Record the current file position before reading.611 # This will allow us to rewind a file in the event612 # of a redirect.613 try:539 self._body_position = body.tell()614 self._body_position = body.tell() # type: ignore[union-attr] # guarded by getattr check615 except OSError:616 # This differentiates from None, allowing us to catch617 # a failed `tell()` later when trying to rewind the body618 self._body_position = object()
7 unmodified lines
626 self.headers["Content-Length"] = builtin_str(length)627 else:628 self.headers["Transfer-Encoding"] = "chunked"629 else:630 # After is_stream filtering, remaining data is raw (not streamed)631 raw_data = cast("_t.RawDataType | None", data)632633 # Multi-part file uploads.634 if files:557 (body, content_type) = self._encode_files(files, data)635 (body, content_type) = self._encode_files(files, raw_data)636 else:559 if data:560 body = self._encode_params(data)561 if isinstance(data, basestring) or hasattr(data, "read"):637 if raw_data:638 body = self._encode_params(raw_data)639 if isinstance(data, basestring) or isinstance(data, _SupportsRead):640 content_type = None641 else:642 content_type = "application/x-www-form-urlencoded"643
2 unmodified lines
646 # Add content-type if it wasn't explicitly provided.647 if content_type and ("content-type" not in self.headers):648 self.headers["Content-Type"] = content_type649572 self.body = body650 self.body = body # type: ignore[assignment] # body transforms from DataType to BodyType651574 def prepare_content_length(self, body):652 def prepare_content_length(self, body: _t.BodyType) -> None:653 """Prepare Content-Length header based on request method and body"""654 if body is not None:655 length = super_len(body)656 if length:
7 unmodified lines
664 # Set Content-Length to 0 for methods that can have a body665 # but don't provide one. (i.e. not GET or HEAD)666 self.headers["Content-Length"] = "0"667590 def prepare_auth(self, auth, url=""):668 def prepare_auth(669 self,670 auth: _t.AuthType,671 url: _t.UriType = "",672 ) -> None:673 """Prepares the given HTTP auth data."""674675 # If no Auth is explicitly provided, extract it from the URL first.676 if auth is None:595 url_auth = get_auth_from_url(self.url)677 url_auth = get_auth_from_url(cast(str, self.url))678 auth = url_auth if any(url_auth) else None679680 if auth:599 if isinstance(auth, tuple) and len(auth) == 2:681 if isinstance(auth, tuple) and len(auth) == 2: # type: ignore[arg-type] # pyright widens tuple from Callable in AuthType682 # special-case basic HTTP auth601 auth = HTTPBasicAuth(*auth)683 auth_handler = HTTPBasicAuth(*auth) # type: ignore[arg-type] # pyright widens tuple from Callable in AuthType684 else:685 # TODO: can be fixed by flipping the conditionals686 auth_handler = cast("Callable[..., PreparedRequest]", auth)687688 # Allow auth to make its changes.604 r = auth(self)689 r = auth_handler(self)690691 # Update self to reflect the auth changes.692 self.__dict__.update(r.__dict__)693694 # Recompute Content-Length695 self.prepare_content_length(self.body)696612 def prepare_cookies(self, cookies):697 def prepare_cookies(698 self, cookies: RequestsCookieJar | CookieJar | dict[str, str] | None699 ) -> None:700 """Prepares the given HTTP cookie data.701702 This function eventually generates a ``Cookie`` header from the703 given cookies using cookielib. Due to cookielib's design, the header
7 unmodified lines
711 self._cookies = cookies712 else:713 self._cookies = cookiejar_from_dict(cookies)714715 cookies_jar = cast("CookieJar", self._cookies)628 cookie_header = get_cookie_header(self._cookies, self)716 cookie_header = get_cookie_header(cookies_jar, self)717 if cookie_header is not None:718 self.headers["Cookie"] = cookie_header719632 def prepare_hooks(self, hooks):720 def prepare_hooks(self, hooks: _t.HooksInputType | None) -> None:721 """Prepares the given hooks."""722 # hooks can be passed as None to the prepare method and to this723 # method. To prevent iterating over None, simply use an empty list724 # if hooks is False-y637 hooks = hooks or []725 hooks = hooks or {}726 for event in hooks:727 self.register_hook(event, hooks[event])728729
1 unmodified line
731 """The :class:`Response <Response>` object, which contains a732 server's response to an HTTP request.733 """734647 __attrs__ = [735 _content: bytes | Literal[False] | None736 _content_consumed: bool737 _next: PreparedRequest | None738 status_code: int739 headers: CaseInsensitiveDict[str]740 raw: Any741 url: str742 encoding: str | None743 history: list[Response]744 reason: str | None745 cookies: RequestsCookieJar746 elapsed: datetime.timedelta747 request: PreparedRequest748 connection: HTTPAdapter749750 __attrs__: list[str] = [751 "_content",752 "status_code",753 "headers",754 "url",
4 unmodified lines
759 "elapsed",760 "request",761 ]762660 def __init__(self):763 def __init__(self) -> None:764 self._content = False765 self._content_consumed = False766 self._next = None767768 #: Integer Code of responded HTTP Status, e.g. 404 or 200.666 self.status_code = None769 self.status_code = None # type: ignore[assignment]770771 #: Case-insensitive Dictionary of Response Headers.772 #: For example, ``headers['content-encoding']`` will return the773 #: value of a ``'Content-Encoding'`` response header.
4 unmodified lines
778 #: This requirement does not apply for use internally to Requests.779 self.raw = None780781 #: Final URL location of Response.679 self.url = None782 self.url = None # type: ignore[assignment]783784 #: Encoding to decode with when accessing r.text.785 self.encoding = None786
17 unmodified lines
804 self.elapsed = datetime.timedelta(0)805806 #: The :class:`PreparedRequest <PreparedRequest>` object to which this807 #: is a response.705 self.request = None808 self.request = None # type: ignore[assignment]809707 def __enter__(self):810 def __enter__(self) -> Self:811 return self812710 def __exit__(self, *args):813 def __exit__(self, *args: Any) -> None:814 self.close()815713 def __getstate__(self):816 def __getstate__(self) -> dict[str, Any]:817 # Consume everything; accessing the content attribute makes818 # sure the content has been fully read.819 if not self._content_consumed:820 self.content821822 return {attr: getattr(self, attr, None) for attr in self.__attrs__}823721 def __setstate__(self, state):824 def __setstate__(self, state: dict[str, Any]) -> None:825 for name, value in state.items():826 setattr(self, name, value)827828 # pickled objects do not have .raw829 setattr(self, "_content_consumed", True)830 setattr(self, "raw", None)831729 def __repr__(self):832 def __repr__(self) -> str:833 return f"<Response [{self.status_code}]>"834732 def __bool__(self):835 def __bool__(self) -> bool:836 """Returns True if :attr:`status_code` is less than 400.837838 This attribute checks if the status code of the response is between839 400 and 600 to see if there was a client error or a server error. If
1 unmodified line
841 is **not** a check to see if the response code is ``200 OK``.842 """843 return self.ok844742 def __nonzero__(self):845 def __nonzero__(self) -> bool:846 """Returns True if :attr:`status_code` is less than 400.847848 This attribute checks if the status code of the response is between849 400 and 600 to see if there was a client error or a server error. If
1 unmodified line
851 is **not** a check to see if the response code is ``200 OK``.852 """853 return self.ok854752 def __iter__(self):855 def __iter__(self) -> Iterator[bytes]:856 """Allows you to use a response as an iterator."""857 return self.iter_content(128)858859 @property757 def ok(self):860 def ok(self) -> bool:861 """Returns True if :attr:`status_code` is less than 400, False if not.862863 This attribute checks if the status code of the response is between864 400 and 600 to see if there was a client error or a server error. If
6 unmodified lines
871 return False872 return True873874 @property772 def is_redirect(self):875 def is_redirect(self) -> bool:876 """True if this Response is a well-formed HTTP redirect that could have877 been processed automatically (by :meth:`Session.resolve_redirects`).878 """879 return "location" in self.headers and self.status_code in REDIRECT_STATI880881 @property779 def is_permanent_redirect(self):882 def is_permanent_redirect(self) -> bool:883 """True if this Response one of the permanent versions of redirect."""884 return "location" in self.headers and self.status_code in (885 codes.moved_permanently,886 codes.permanent_redirect,887 )888889 @property787 def next(self):890 def next(self) -> PreparedRequest | None:891 """Returns a PreparedRequest for the next request in a redirect chain, if there is one."""892 return self._next893894 @property792 def apparent_encoding(self):895 def apparent_encoding(self) -> str | None:896 """The apparent encoding, provided by the charset_normalizer or chardet libraries."""897 if chardet is not None:898 return chardet.detect(self.content)["encoding"]899 else:900 # If no character detection library is available, we'll fall back901 # to a standard Python utf-8 str.902 return "utf-8"903801 def iter_content(self, chunk_size=1, decode_unicode=False):904 @overload905 def iter_content(906 self, chunk_size: int | None = 1, decode_unicode: Literal[False] = False907 ) -> Iterator[bytes]: ...908 @overload909 def iter_content(910 self, chunk_size: int | None = 1, *, decode_unicode: Literal[True]911 ) -> Iterator[str | bytes]: ...912 def iter_content(913 self, chunk_size: int | None = 1, decode_unicode: bool = False914 ) -> Iterator[str | bytes]:915 """Iterates over the response data. When stream=True is set on the916 request, this avoids reading the content at once into memory for917 large responses. The chunk size is the number of bytes it should918 read into memory. This is not necessarily the length of each item
10 unmodified lines
929 bytes will be returned. This can be bypassed by manually setting930 `encoding` on the response.931 """932820 def generate():933 def generate() -> Generator[bytes, None, None]:934 # Special case for urllib3.935 if hasattr(self.raw, "stream"):936 try:937 yield from self.raw.stream(chunk_size, decode_content=True)
16 unmodified lines
954 self._content_consumed = True955956 if self._content_consumed and isinstance(self._content, bool):957 raise StreamConsumedError()845 elif chunk_size is not None and not isinstance(chunk_size, int):958 elif chunk_size is not None and not isinstance(chunk_size, int): # type: ignore[reportUnnecessaryIsInstance] # runtime guard for untyped callers959 raise TypeError(960 f"chunk_size must be an int, it is instead a {type(chunk_size)}."961 )849 # simulate reading small chunks of the content850 reused_chunks = iter_slices(self._content, chunk_size)962963 if self._content_consumed:964 # simulate reading small chunks of the content965 content = cast(bytes, self._content)966 chunks = iter_slices(content, chunk_size)967 else:852 stream_chunks = generate()968 chunks = generate()969854 chunks = reused_chunks if self._content_consumed else stream_chunks855970 if decode_unicode:971 chunks = stream_decode_response_unicode(chunks, self)972973 return chunks974975 @overload976 def iter_lines(862 self, chunk_size=ITER_CHUNK_SIZE, decode_unicode=False, delimiter=None863 ):977 self,978 chunk_size: int = ITER_CHUNK_SIZE,979 decode_unicode: Literal[False] = False,980 delimiter: bytes | None = None,981 ) -> Iterator[bytes]: ...982 @overload983 def iter_lines(984 self,985 chunk_size: int = ITER_CHUNK_SIZE,986 *,987 decode_unicode: Literal[True],988 delimiter: str | bytes | None = None,989 ) -> Iterator[str | bytes]: ...990 def iter_lines(991 self,992 chunk_size: int = ITER_CHUNK_SIZE,993 decode_unicode: bool = False,994 delimiter: str | bytes | None = None,995 ) -> Iterator[str | bytes]:996 """Iterates over the response data, one line at a time. When997 stream=True is set on the request, this avoids reading the998 content at once into memory for large responses.999
2 unmodified lines
10021003 .. note:: This method is not reentrant safe.1004 """1005874 pending = None1006 pending: str | bytes | None = None10071008 for chunk in self.iter_content(1009 chunk_size=chunk_size, decode_unicode=decode_unicode1010 ):1011 if pending is not None:880 chunk = pending + chunk1012 # TODO: remove cast after iter_lines rewrite1013 chunk = cast("str | bytes", pending + chunk) # type: ignore[operator]10141015 if delimiter:883 lines = chunk.split(delimiter)1016 lines = chunk.split(delimiter) # type: ignore[arg-type]1017 else:1018 lines = chunk.splitlines()10191020 if lines and lines[-1] and chunk and lines[-1][-1] == chunk[-1]:
6 unmodified lines
1027 if pending is not None:1028 yield pending10291030 @property898 def content(self):1031 def content(self) -> bytes:1032 """Content of the response, in bytes."""10331034 if self._content is False:1035 # Read the contents.
7 unmodified lines
10431044 self._content_consumed = True1045 # don't need to release the connection; that's been handled by urllib31046 # since we exhausted the data.914 return self._content1047 return self._content # type: ignore[return-value]10481049 @property917 def text(self):1050 def text(self) -> str:1051 """Content of the response, in unicode.10521053 If Response.encoding is None, encoding will be guessed using1054 ``charset_normalizer`` or ``chardet``.
16 unmodified lines
1071 encoding = self.apparent_encoding10721073 # Decode unicode from given encoding.1074 try:942 content = str(self.content, encoding, errors="replace")1075 content = str(self.content, encoding or "utf-8", errors="replace")1076 except (LookupError, TypeError):1077 # A LookupError is raised if the encoding was not found which could1078 # indicate a misspelling or similar mistake.1079 #
3 unmodified lines
1083 content = str(self.content, errors="replace")10841085 return content1086954 def json(self, **kwargs):1087 def json(self, **kwargs: Any) -> Any:1088 r"""Decodes the JSON response body (if any) as a Python object.10891090 This may return a dictionary, list, etc. depending on what is in the response.1091
27 unmodified lines
1119 # This aliases json.JSONDecodeError and simplejson.JSONDecodeError1120 raise RequestsJSONDecodeError(e.msg, e.doc, e.pos)11211122 @property990 def links(self):1123 def links(self) -> dict[str, dict[str, str]]:1124 """Returns the parsed header links of the response, if any."""11251126 header = self.headers.get("link")1127995 resolved_links = {}1128 resolved_links: dict[str, dict[str, str]] = {}11291130 if header:1131 links = parse_header_links(header)11321133 for link in links:1134 key = link.get("rel") or link.get("url")1135 if key is not None:1002 resolved_links[key] = link1136 resolved_links[key] = link11371138 return resolved_links11391006 def raise_for_status(self):1140 def raise_for_status(self) -> None:1141 """Raises :class:`HTTPError`, if one occurred."""11421143 http_error_msg = ""1144 if isinstance(self.reason, bytes):
20 unmodified lines
11651166 if http_error_msg:1167 raise HTTPError(http_error_msg, response=self)11681035 def close(self):1169 def close(self) -> None:1170 """Releases the connection back to the pool. Once this method has been1171 called the underlying ``raw`` object must not be accessed again.11721173 *Note: Should not normally need to be called explicitly.*
7 unmodified lines
added:src/requests/py.typed
modified:src/requests/sessions.py+155 added-75 removed
4 unmodified lines
5This module provides a Session object to manage and persist settings across6requests (cookies, auth, proxies).7"""89from __future__ import annotations1011import os12import sys13import time14from collections import OrderedDict15from collections.abc import Generator, Mapping, MutableMapping16from datetime import timedelta17from typing import TYPE_CHECKING, Any, cast1819from ._internal_utils import to_native_string20from ._types import is_prepared as _is_prepared21from .adapters import HTTPAdapter17from .auth import _basic_auth_str18from .compat import Mapping, cookielib, urljoin, urlparse22from .auth import _basic_auth_str # type: ignore[reportPrivateUsage]23from .compat import cookielib, urljoin, urlparse24from .cookies import (25 RequestsCookieJar,26 cookiejar_from_dict,27 extract_cookies_to_jar,
9 unmodified lines
3738# formerly defined here, reexposed here for backward compatibility39from .models import ( # noqa: F40140 DEFAULT_REDIRECT_LIMIT,36 REDIRECT_STATI,41 REDIRECT_STATI, # type: ignore[reportUnusedImport]42 PreparedRequest,43 Request,44 Response,45)46from .status_codes import codes47from .structures import CaseInsensitiveDict48from .utils import ( # noqa: F401
4 unmodified lines
53 get_netrc_auth,54 requote_uri,55 resolve_proxies,56 rewind_body,51 should_bypass_proxies,57 should_bypass_proxies, # type: ignore[reportUnusedImport] # re-export for external consumers58 to_key_val_list,59)6061if TYPE_CHECKING:62 from http.cookiejar import CookieJar6364 from typing_extensions import Self, Unpack6566 from . import _types as _t67 from .adapters import BaseAdapter6869# Preferred clock, based on which one is more accurate on a given system.70if sys.platform == "win32":71 preferred_clock = time.perf_counter72else:73 preferred_clock = time.time747562def merge_setting(request_setting, session_setting, dict_class=OrderedDict):76def merge_setting(77 request_setting: Any, session_setting: Any, dict_class: type = OrderedDict78) -> Any:79 """Determines appropriate setting for a given request, taking into account80 the explicit setting on that request, and the setting in the session. If a81 setting is a dictionary, they will be merged together using `dict_class`82 """
9 unmodified lines
92 isinstance(session_setting, Mapping) and isinstance(request_setting, Mapping)93 ):94 return request_setting9580 merged_setting = dict_class(to_key_val_list(session_setting))81 merged_setting.update(to_key_val_list(request_setting))96 merged_setting = dict_class(to_key_val_list(session_setting)) # type: ignore[arg-type] # isinstance narrows Any to Mapping[Unknown]97 merged_setting.update(to_key_val_list(request_setting)) # type: ignore[arg-type]9899 # Remove keys that are set to None. Extract keys first to avoid altering100 # the dictionary during iteration.101 none_keys = [k for (k, v) in merged_setting.items() if v is None]
2 unmodified lines
104105 return merged_setting10610792def merge_hooks(request_hooks, session_hooks, dict_class=OrderedDict):108def merge_hooks(109 request_hooks: _t.HooksType,110 session_hooks: _t.HooksType,111 dict_class: type = OrderedDict,112) -> _t.HooksType:113 """Properly merges both requests and session hooks.114115 This is necessary because when request_hooks == {'response': []}, the116 merge breaks Session hooks entirely.
7 unmodified lines
124 return merge_setting(request_hooks, session_hooks, dict_class)125126127class SessionRedirectMixin:128 max_redirects: int129 trust_env: bool130 cookies: RequestsCookieJar131132 def send(self, request: PreparedRequest, **kwargs: Any) -> Response: ...133108 def get_redirect_target(self, resp):134 def get_redirect_target(self, resp: Response) -> str | None:135 """Receives a Response. Returns a redirect URI or ``None``"""136 # Due to the nature of how requests processes redirects this method will137 # be called at least once upon the original response and at least twice138 # on each subsequent redirect response (if any).
11 unmodified lines
150 location = location.encode("latin1")151 return to_native_string(location, "utf8")152 return None153128 def should_strip_auth(self, old_url, new_url):154 def should_strip_auth(self, old_url: str, new_url: str) -> bool:155 """Decide whether Authorization header should be removed when redirecting"""156 old_parsed = urlparse(old_url)157 new_parsed = urlparse(new_url)158 if old_parsed.hostname != new_parsed.hostname:
25 unmodified lines
184 return changed_port or changed_scheme185186 def resolve_redirects(187 self,162 resp,163 req,164 stream=False,165 timeout=None,166 verify=True,167 cert=None,168 proxies=None,169 yield_requests=False,170 **adapter_kwargs,171 ):188 resp: Response,189 req: PreparedRequest,190 stream: bool = False,191 timeout: _t.TimeoutType = None,192 verify: _t.VerifyType = True,193 cert: _t.CertType = None,194 proxies: dict[str, str] | None = None,195 yield_requests: bool = False,196 **adapter_kwargs: Any,197 ) -> Generator[Response, None, None]:198 """Receives a Response. Returns a generator of Responses or Requests."""199174 hist = [] # keep track of history200 hist: list[Response] = [] # keep track of history201202 url = self.get_redirect_target(resp)203 previous_fragment = urlparse(req.url).fragment204 while url:
57 unmodified lines
262263 # Extract any cookies sent on the response to the cookiejar264 # in the new request. Because we've mutated our copied prepared265 # request, use the old one that we haven't yet touched.266 cookie_jar = cast("CookieJar", prepared_request._cookies) # type: ignore[reportPrivateUsage]240 extract_cookies_to_jar(prepared_request._cookies, req, resp.raw)241 merge_cookies(prepared_request._cookies, self.cookies)242 prepared_request.prepare_cookies(prepared_request._cookies)267 extract_cookies_to_jar(cookie_jar, req, resp.raw)268 merge_cookies(cookie_jar, self.cookies)269 prepared_request.prepare_cookies(cookie_jar)270271 # Rebuild auth and proxy information.272 proxies = self.rebuild_proxies(prepared_request, proxies)273 self.rebuild_auth(prepared_request, resp)274275 # A failed tell() sets `_body_position` to `object()`. This non-None276 # value ensures `rewindable` will be True, allowing us to raise an277 # UnrewindableBodyError, instead of hanging the connection.251 rewindable = prepared_request._body_position is not None and (278 rewindable = prepared_request._body_position is not None and ( # type: ignore[reportPrivateUsage]279 "Content-Length" in headers or "Transfer-Encoding" in headers280 )281282 # Attempt to rewind consumed file-like object.
3 unmodified lines
286 # Override the original request.287 req = prepared_request288289 if yield_requests:263 yield req290 yield req # type: ignore[misc] # Internal use only, returns PreparedRequest291 else:292 resp = self.send(293 req,294 stream=stream,
10 unmodified lines
305 # extract redirect url, if any, for the next loop306 url = self.get_redirect_target(resp)307 yield resp308282 def rebuild_auth(self, prepared_request, response):309 def rebuild_auth(310 self, prepared_request: PreparedRequest, response: Response311 ) -> None:312 """When being redirected we may want to strip authentication from the313 request to avoid leaking credentials. This method intelligently removes314 and reapplies authentication where possible to avoid credential loss.315 """316 original_request = response.request317 assert _is_prepared(original_request)318 assert _is_prepared(prepared_request)319320 headers = prepared_request.headers321 original_url = original_request.url322 url = prepared_request.url323290 if "Authorization" in headers and self.should_strip_auth(291 response.request.url, url292 ):324 if "Authorization" in headers and self.should_strip_auth(original_url, url):325 # If we get redirected to a new host, we should strip out any326 # authentication headers.327 del headers["Authorization"]328
1 unmodified line
330 new_auth = get_netrc_auth(url) if self.trust_env else None331 if new_auth is not None:332 prepared_request.prepare_auth(new_auth)333302 def rebuild_proxies(self, prepared_request, proxies):334 def rebuild_proxies(335 self,336 prepared_request: PreparedRequest,337 proxies: dict[str, str] | None,338 ) -> dict[str, str]:339 """This method re-evaluates the proxy configuration by considering the340 environment variables. If we are redirected to a URL covered by341 NO_PROXY, we strip the proxy configuration. Otherwise, we set missing342 proxy keys for this URL (in case they were stripped by a previous
3 unmodified lines
346 necessary.347348 :rtype: dict349 """350 assert _is_prepared(prepared_request)351 headers = prepared_request.headers352 scheme = urlparse(prepared_request.url).scheme353 new_proxies = resolve_proxies(prepared_request, proxies, self.trust_env)354
11 unmodified lines
366 headers["Proxy-Authorization"] = _basic_auth_str(username, password)367368 return new_proxies369333 def rebuild_method(self, prepared_request, response):370 def rebuild_method(371 self, prepared_request: PreparedRequest, response: Response372 ) -> None:373 """When being redirected we may want to change the method of the request374 based on certain specs or browser behavior.375 """376 method = prepared_request.method
33 unmodified lines
410 ... s.get('https://httpbin.org/get')411 <Response [200]>412 """413414 headers: CaseInsensitiveDict[str]415 auth: _t.AuthType416 proxies: dict[str, str]417 hooks: dict[str, list[_t.HookType]]418 params: MutableMapping[str, Any]419 stream: bool420 verify: _t.VerifyType421 cert: _t.CertType422 max_redirects: int423 trust_env: bool424 cookies: RequestsCookieJar425 adapters: MutableMapping[str, BaseAdapter]426375 __attrs__ = [427 __attrs__: list[str] = [428 "headers",429 "cookies",430 "auth",431 "proxies",
6 unmodified lines
438 "trust_env",439 "max_redirects",440 ]441390 def __init__(self):442 def __init__(self) -> None:443 #: A case-insensitive dictionary of headers to be sent on each444 #: :class:`Request <Request>` sent from this445 #: :class:`Session <Session>`.446 self.headers = default_headers()
54 unmodified lines
501 self.adapters = OrderedDict()502 self.mount("https://", HTTPAdapter())503 self.mount("http://", HTTPAdapter())504453 def __enter__(self):505 def __enter__(self) -> Self:506 return self507456 def __exit__(self, *args):508 def __exit__(self, *args: Any) -> None:509 self.close()510459 def prepare_request(self, request):511 def prepare_request(self, request: Request) -> PreparedRequest:512 """Constructs a :class:`PreparedRequest <PreparedRequest>` for513 transmission and returns it. The :class:`PreparedRequest` has settings514 merged from the :class:`Request <Request>` instance and those of the515 :class:`Session`.
1 unmodified line
517 :param request: :class:`Request` instance to prepare with this518 session's settings.519 :rtype: requests.PreparedRequest520 """521 url = cast("_t.UriType", request.url)522 method = cast(str, request.method)523524 cookies = request.cookies or {}525526 # Bootstrap CookieJar.527 if not isinstance(cookies, cookielib.CookieJar):
6 unmodified lines
534535 # Set environment's basic authentication if not explicitly set.536 auth = request.auth537 if self.trust_env and not auth and not self.auth:483 auth = get_netrc_auth(request.url)538 auth = get_netrc_auth(url)539540 p = PreparedRequest()541 p.prepare(487 method=request.method.upper(),488 url=request.url,542 method=method.upper(),543 url=url,544 files=request.files,545 data=request.data,546 json=request.json,547 headers=merge_setting(
7 unmodified lines
555 return p556557 def request(558 self,504 method,505 url,506 params=None,507 data=None,508 headers=None,509 cookies=None,510 files=None,511 auth=None,512 timeout=None,513 allow_redirects=True,514 proxies=None,515 hooks=None,516 stream=None,517 verify=None,518 cert=None,519 json=None,520 ):559 method: str,560 url: _t.UriType,561 params: _t.ParamsType = None,562 data: _t.DataType = None,563 headers: Mapping[str, str | bytes] | None = None,564 cookies: RequestsCookieJar | CookieJar | dict[str, str] | None = None,565 files: _t.FilesType = None,566 auth: _t.AuthType = None,567 timeout: _t.TimeoutType = None,568 allow_redirects: bool = True,569 proxies: dict[str, str] | None = None,570 hooks: _t.HooksType = None,571 stream: bool | None = None,572 verify: _t.VerifyType | None = None,573 cert: _t.CertType = None,574 json: _t.JsonType = None,575 ) -> Response:576 """Constructs a :class:`Request <Request>`, prepares it and sends it.577 Returns :class:`Response <Response>` object.578579 :param method: method for the new :class:`Request` object.
35 unmodified lines
615 :param cert: (optional) if String, path to ssl client cert file (.pem).616 If Tuple, ('cert', 'key') pair.617 :rtype: requests.Response618 """619 if isinstance(url, bytes):620 url = url.decode("utf-8")621622 # Create the Request.623 req = Request(624 method=method.upper(),625 url=url,
7 unmodified lines
633 hooks=hooks,634 )635 prep = self.prepare_request(req)636637 assert _is_prepared(prep)638639 proxies = proxies or {}640641 settings = self.merge_environment_settings(642 prep.url, proxies, stream, verify, cert
8 unmodified lines
651 resp = self.send(prep, **send_kwargs)652653 return resp654595 def get(self, url, **kwargs):655 def get(self, url: _t.UriType, **kwargs: Unpack[_t.GetKwargs]) -> Response:656 r"""Sends a GET request. Returns :class:`Response` object.657658 :param url: URL for the new :class:`Request` object.659 :param \*\*kwargs: Optional arguments that ``request`` takes.
2 unmodified lines
662663 kwargs.setdefault("allow_redirects", True)664 return self.request("GET", url, **kwargs)665606 def options(self, url, **kwargs):666 def options(self, url: _t.UriType, **kwargs: Unpack[_t.RequestKwargs]) -> Response:667 r"""Sends a OPTIONS request. Returns :class:`Response` object.668669 :param url: URL for the new :class:`Request` object.670 :param \*\*kwargs: Optional arguments that ``request`` takes.
2 unmodified lines
673674 kwargs.setdefault("allow_redirects", True)675 return self.request("OPTIONS", url, **kwargs)676617 def head(self, url, **kwargs):677 def head(self, url: _t.UriType, **kwargs: Unpack[_t.RequestKwargs]) -> Response:678 r"""Sends a HEAD request. Returns :class:`Response` object.679680 :param url: URL for the new :class:`Request` object.681 :param \*\*kwargs: Optional arguments that ``request`` takes.
2 unmodified lines
684685 kwargs.setdefault("allow_redirects", False)686 return self.request("HEAD", url, **kwargs)687628 def post(self, url, data=None, json=None, **kwargs):688 def post(689 self,690 url: _t.UriType,691 data: _t.DataType = None,692 json: _t.JsonType = None,693 **kwargs: Unpack[_t.PostKwargs],694 ) -> Response:695 r"""Sends a POST request. Returns :class:`Response` object.696697 :param url: URL for the new :class:`Request` object.698 :param data: (optional) Dictionary, list of tuples, bytes, or file-like
4 unmodified lines
703 """704705 return self.request("POST", url, data=data, json=json, **kwargs)706641 def put(self, url, data=None, **kwargs):707 def put(708 self, url: _t.UriType, data: _t.DataType = None, **kwargs: Unpack[_t.DataKwargs]709 ) -> Response:710 r"""Sends a PUT request. Returns :class:`Response` object.711712 :param url: URL for the new :class:`Request` object.713 :param data: (optional) Dictionary, list of tuples, bytes, or file-like
3 unmodified lines
717 """718719 return self.request("PUT", url, data=data, **kwargs)720653 def patch(self, url, data=None, **kwargs):721 def patch(722 self, url: _t.UriType, data: _t.DataType = None, **kwargs: Unpack[_t.DataKwargs]723 ) -> Response:724 r"""Sends a PATCH request. Returns :class:`Response` object.725726 :param url: URL for the new :class:`Request` object.727 :param data: (optional) Dictionary, list of tuples, bytes, or file-like
3 unmodified lines
731 """732733 return self.request("PATCH", url, data=data, **kwargs)734665 def delete(self, url, **kwargs):735 def delete(self, url: _t.UriType, **kwargs: Unpack[_t.RequestKwargs]) -> Response:736 r"""Sends a DELETE request. Returns :class:`Response` object.737738 :param url: URL for the new :class:`Request` object.739 :param \*\*kwargs: Optional arguments that ``request`` takes.
1 unmodified line
741 """742743 return self.request("DELETE", url, **kwargs)744675 def send(self, request, **kwargs):745 def send(self, request: PreparedRequest, **kwargs: Any) -> Response:746 """Send a given PreparedRequest.747748 :rtype: requests.Response749 """
9 unmodified lines
759 # Guard against that specific failure case.760 if isinstance(request, Request):761 raise ValueError("You can only send PreparedRequests.")762763 assert _is_prepared(request)764765 # Set up variables needed for resolve_redirects and dispatching of hooks766 allow_redirects = kwargs.pop("allow_redirects", True)767 stream = kwargs.get("stream")768 hooks = request.hooks
40 unmodified lines
809810 # If redirects aren't being followed, store the response on the Request for Response.next().811 if not allow_redirects:812 try:741 r._next = next(813 r._next = next( # type: ignore[assignment] # yield_requests=True returns PreparedRequest814 self.resolve_redirects(r, request, yield_requests=True, **kwargs)815 )816 except StopIteration:817 pass
2 unmodified lines
820 r.content821822 return r823752 def merge_environment_settings(self, url, proxies, stream, verify, cert):824 def merge_environment_settings(825 self,826 url: str,827 proxies: dict[str, str] | None,828 stream: bool | None,829 verify: _t.VerifyType | None,830 cert: _t.CertType,831 ) -> dict[str, Any]:832 """833 Check the environment and merge it with some settings.834835 :rtype: dict
2 unmodified lines
838 if self.trust_env:839 # Set environment's proxies.840 no_proxy = proxies.get("no_proxy") if proxies is not None else None841 env_proxies = get_environ_proxies(url, no_proxy=no_proxy)842 if proxies is not None:763 for k, v in env_proxies.items():764 proxies.setdefault(k, v)843 for k, v in env_proxies.items():844 proxies.setdefault(k, v)845846 # Look for requests environment configuration847 # and be compatible with cURL.848 if verify is True or verify is None:
10 unmodified lines
859 cert = merge_setting(cert, self.cert)860861 return {"proxies": proxies, "stream": stream, "verify": verify, "cert": cert}862783 def get_adapter(self, url):863 def get_adapter(self, url: str) -> BaseAdapter:864 """865 Returns the appropriate connection adapter for the given URL.866867 :rtype: requests.adapters.BaseAdapter
4 unmodified lines
872873 # Nothing matches :-/874 raise InvalidSchema(f"No connection adapters were found for {url!r}")875796 def close(self):876 def close(self) -> None:877 """Closes all adapters and as such the session"""878 for v in self.adapters.values():879 v.close()880801 def mount(self, prefix, adapter):881 def mount(self, prefix: str, adapter: BaseAdapter) -> None:882 """Registers a connection adapter to a prefix.883884 Adapters are sorted in descending order by prefix length.885 """
2 unmodified lines
888889 for key in keys_to_move:890 self.adapters[key] = self.adapters.pop(key)891812 def __getstate__(self):892 def __getstate__(self) -> dict[str, Any]:893 state = {attr: getattr(self, attr, None) for attr in self.__attrs__}894 return state895816 def __setstate__(self, state):896 def __setstate__(self, state: dict[str, Any]) -> None:897 for attr, value in state.items():898 setattr(self, attr, value)899900821def session():901def session() -> Session:902 """903 Returns a :class:`Session` for context-management.904905 .. deprecated:: 1.0.0
8 unmodified lines
modified:src/requests/status_codes.py+2 added-2 removed
101 unmodified lines
102 510: ("not_extended",),103 511: ("network_authentication_required", "network_auth", "network_authentication"),104}105106codes = LookupDict(name="status_codes")106codes: LookupDict[int] = LookupDict(name="status_codes")107108109def _init():110 for code, titles in _codes.items():
1 unmodified line
112 setattr(codes, title, code)113 if not title.startswith(("\\", "/")):114 setattr(codes, title.upper(), code)115116 def doc(code):116 def doc(code: int) -> str:117 names = ", ".join(f"``{n}``" for n in _codes[code])118 return "* %d: %s" % (code, names)119120 global __doc__
8 unmodified lines
modified:src/requests/structures.py+51 added-20 removed
3 unmodified lines
45Data structures that power Requests.6"""78from __future__ import annotations910from collections import OrderedDict11from collections.abc import Iterable, Iterator, Mapping12from typing import Any, Generic, TypeVar, overload1310from .compat import Mapping, MutableMapping14from .compat import MutableMapping1516_VT = TypeVar("_VT")17_D = TypeVar("_D")181913class CaseInsensitiveDict(MutableMapping):20class CaseInsensitiveDict(MutableMapping[str, _VT], Generic[_VT]):21 """A case-insensitive ``dict``-like object.2223 Implements all methods and operations of24 ``MutableMapping`` as well as dict's ``copy``. Also
18 unmodified lines
43 operations are given keys that have equal ``.lower()``s, the44 behavior is undefined.45 """4640 def __init__(self, data=None, **kwargs):47 _store: OrderedDict[str, tuple[str, _VT]]4849 def __init__(50 self,51 data: Mapping[str, _VT] | Iterable[tuple[str, _VT]] | None = None,52 **kwargs: _VT,53 ) -> None:54 self._store = OrderedDict()55 if data is None:56 data = {}57 self.update(data, **kwargs)5846 def __setitem__(self, key, value):59 def __setitem__(self, key: str, value: _VT) -> None:60 # Use the lowercased key for lookups, but store the actual61 # key alongside the value.62 self._store[key.lower()] = (key, value)6351 def __getitem__(self, key):64 def __getitem__(self, key: str) -> _VT:65 return self._store[key.lower()][1]6654 def __delitem__(self, key):67 def __delitem__(self, key: str) -> None:68 del self._store[key.lower()]6957 def __iter__(self):58 return (casedkey for casedkey, mappedvalue in self._store.values())70 def __iter__(self) -> Iterator[str]:71 return (casedkey for casedkey, _ in self._store.values())7260 def __len__(self):73 def __len__(self) -> int:74 return len(self._store)7563 def lower_items(self):76 def lower_items(self) -> Iterator[tuple[str, _VT]]:77 """Like iteritems(), but with all lowercase keys."""78 return ((lowerkey, keyval[1]) for (lowerkey, keyval) in self._store.items())7967 def __eq__(self, other):80 def __eq__(self, other: object) -> bool:81 if isinstance(other, Mapping):69 other = CaseInsensitiveDict(other)82 other_dict: CaseInsensitiveDict[Any] = CaseInsensitiveDict(other) # type: ignore[reportUnknownArgumentType]83 else:84 return NotImplemented85 # Compare insensitively73 return dict(self.lower_items()) == dict(other.lower_items())86 return dict(self.lower_items()) == dict(other_dict.lower_items())8788 # Copy is required76 def copy(self):89 def copy(self) -> CaseInsensitiveDict[_VT]:90 return CaseInsensitiveDict(self._store.values())9179 def __repr__(self):92 def __repr__(self) -> str:93 return str(dict(self.items()))949583class LookupDict(dict):96class LookupDict(dict[str, _VT]):97 """Dictionary lookup object."""9899 name: Any10086 def __init__(self, name=None):101 def __init__(self, name: Any = None) -> None:102 self.name = name103 super().__init__()10490 def __repr__(self):105 def __repr__(self) -> str:106 return f"<lookup '{self.name}'>"10793 def __getitem__(self, key):108 def __getattr__(self, key: str) -> _VT | None:109 # We need this for type checkers to infer typing110 # on attribute access with status_codes.py111 if key in self.__dict__:112 return self.__dict__[key]113 else:114 raise AttributeError(115 f"'{type(self).__name__}' object has no attribute '{key}'"116 )117118 def __getitem__(self, key: str) -> _VT | None: # type: ignore[override]119 # We allow fall-through here, so values default to None120121 return self.__dict__.get(key, None)12298 def get(self, key, default=None):123 @overload124 def get(self, key: str, default: None = None) -> _VT | None: ...125126 @overload127 def get(self, key: str, default: _D | _VT) -> _D | _VT: ...128129 def get(self, key: str, default: _D | None = None) -> _VT | _D | None:130 return self.__dict__.get(key, default)
modified:src/requests/utils.py+157 added-87 removed
4 unmodified lines
5This module provides utility functions that are used within Requests6that are also useful for external consumption.7"""89from __future__ import annotations1011import codecs12import contextlib13import io14import os
4 unmodified lines
19import tempfile20import warnings21import zipfile22from collections import OrderedDict23from collections.abc import Generator, Iterable24from typing import (25 TYPE_CHECKING,26 Any,27 Final,28 TypeVar,29 cast,30 overload,31)3233from urllib3.util import make_headers, parse_url3435from . import certs36from .__version__ import __version__3738# to_native_string is unused here, but imported here for backwards compatibility39from ._internal_utils import ( # noqa: F40129 _HEADER_VALIDATORS_BYTE,30 _HEADER_VALIDATORS_STR,31 HEADER_VALIDATORS,32 to_native_string,40 _HEADER_VALIDATORS_BYTE, # type: ignore[reportPrivateUsage]41 _HEADER_VALIDATORS_STR, # type: ignore[reportPrivateUsage]42 HEADER_VALIDATORS, # type: ignore[reportUnusedImport]43 to_native_string, # type: ignore[reportUnusedImport]44)45from ._types import SupportsItems as _SupportsItems46from .compat import (47 Mapping,36 basestring,48 bytes,49 getproxies,50 getproxies_environment,51 integer_types,52 is_urllib3_1,53 proxy_bypass,43 proxy_bypass_environment,54 proxy_bypass_environment, # type: ignore[attr-defined] # https://github.com/python/cpython/issues/14533155 quote,56 str,57 unquote,58 urlparse,
8 unmodified lines
67 UnrewindableBodyError,68)69from .structures import CaseInsensitiveDict7060NETRC_FILES = (".netrc", "_netrc")71if TYPE_CHECKING:72 from http.cookiejar import CookieJar73 from io import BufferedWriter7475 from . import _types as _t76 from .models import PreparedRequest, Request, Response7778NETRC_FILES: Final = (".netrc", "_netrc")798081# Certificate is extracted by certifi when needed.63DEFAULT_CA_BUNDLE_PATH = certs.where()82DEFAULT_CA_BUNDLE_PATH: str = certs.where()8365DEFAULT_PORTS = {"http": 80, "https": 443}8485DEFAULT_PORTS: Final = {"http": 80, "https": 443}8687_KT = TypeVar("_KT")88_VT = TypeVar("_VT")8990# Ensure that ', ' is used to preserve previous delimiter behavior.68DEFAULT_ACCEPT_ENCODING = ", ".join(91DEFAULT_ACCEPT_ENCODING: Final = ", ".join(92 re.split(r",\s*", make_headers(accept_encoding=True)["accept-encoding"])93)949596if sys.platform == "win32":97 # provide a proxy_bypass version on Windows without DNS lookups9876 def proxy_bypass_registry(host):99 def proxy_bypass_registry(host: str) -> bool:100 try:101 import winreg102 except ImportError:103 return False
29 unmodified lines
133 if re.match(test, host, re.I):134 return True135 return False136114 def proxy_bypass(host): # noqa137 def proxy_bypass(host: str) -> bool: # noqa138 """Return True, if the host should be bypassed.139140 Checks proxy settings gathered from the environment, if specified,141 or the registry.
3 unmodified lines
145 else:146 return proxy_bypass_registry(host)147148126def dict_to_sequence(d):149def dict_to_sequence(150 d: _t.SupportsItems | Iterable[tuple[Any, Any]],151) -> Iterable[tuple[Any, Any]]:152 """Returns an internal sequence dictionary update."""153129 if hasattr(d, "items"):130 d = d.items()154 if isinstance(d, _SupportsItems):155 return d.items()156157 return d158159135def super_len(o):160def super_len(o: Any) -> int:161 total_length = None162 current_position = 0163164 if not is_urllib3_1 and isinstance(o, str):
62 unmodified lines
227228 return max(0, total_length - current_position)229230206def get_netrc_auth(url, raise_errors=False):231def get_netrc_auth(232 url: _t.UriType, raise_errors: bool = False233) -> tuple[str, str] | None:234 """Returns the Requests tuple auth for a given url from netrc."""235236 if isinstance(url, bytes):237 url = url.decode("utf-8")238239 netrc_file = os.environ.get("NETRC")240 if netrc_file is not None:241 netrc_locations = (netrc_file,)242 else:
16 unmodified lines
259260 ri = urlparse(url)261 host = ri.hostname262263 if host is None:264 return265266 try:267 _netrc = netrc(netrc_path).authenticators(host)268 if _netrc and any(_netrc):269 # Return with login / password270 login_i = 0 if _netrc[0] else 1238 return (_netrc[login_i], _netrc[2])271 return (_netrc[login_i] or "", _netrc[2] or "")272 except (NetrcParseError, OSError):273 # If there was a parsing error or a permissions issue reading the file,274 # we'll just skip netrc auth unless explicitly asked to raise errors.275 if raise_errors:
3 unmodified lines
279 except (ImportError, AttributeError):280 pass281282250def guess_filename(obj):283def guess_filename(obj: Any) -> str | None:284 """Tries to guess the filename of the given object."""285 name = getattr(obj, "name", None)253 if name and isinstance(name, basestring) and name[0] != "<" and name[-1] != ">":254 return os.path.basename(name)286 if name and isinstance(name, (str, bytes)) and name[0] != "<" and name[-1] != ">":287 return os.path.basename(name) # type: ignore[return-value] # urllib3 accepts bytes but types str only288289257def extract_zipped_paths(path):290def extract_zipped_paths(path: str) -> str:291 """Replace nonexistent paths that look like they refer to a member of a zip292 archive with the location of an extracted copy of the target, or else293 just return the provided path unchanged.294 """
30 unmodified lines
325 return extracted_path326327328@contextlib.contextmanager296def atomic_open(filename):329def atomic_open(filename: str) -> Generator[BufferedWriter, None, None]:330 """Write a file to the disk in an atomic fashion"""331 tmp_descriptor, tmp_name = tempfile.mkstemp(dir=os.path.dirname(filename))332 try:333 with os.fdopen(tmp_descriptor, "wb") as tmp_handler:
3 unmodified lines
337 os.remove(tmp_name)338 raise339340308def from_key_val_list(value):341def from_key_val_list(342 value: Mapping[Any, Any] | Iterable[tuple[Any, Any]] | None,343) -> dict[Any, Any] | None:344 """Take an object and test to see if it can be represented as a345 dictionary. Unless it can not be represented as such, return an346 OrderedDict, e.g.,347
18 unmodified lines
366367 return OrderedDict(value)368369370@overload371def to_key_val_list(value: None) -> None: ...372@overload335def to_key_val_list(value):373def to_key_val_list(374 value: Mapping[_KT, _VT] | Iterable[tuple[_KT, _VT]],375) -> list[tuple[_KT, _VT]]: ...376def to_key_val_list(377 value: Mapping[_KT, _VT] | Iterable[tuple[_KT, _VT]] | None,378) -> list[tuple[_KT, _VT]] | None:379 """Take an object and test to see if it can be represented as a380 dictionary. If it can be, return a list of tuples, e.g.,381382 ::
14 unmodified lines
397398 if isinstance(value, (str, bytes, bool, int)):399 raise ValueError("cannot encode objects that are not 2-tuples")400358 if isinstance(value, Mapping):359 value = value.items()401 if isinstance(value, _SupportsItems):402 return list(value.items())403404 return list(value)405406407# From mitsuhiko/werkzeug (used with permission).365def parse_list_header(value):408def parse_list_header(value: str) -> list[str]:409 """Parse lists as described by RFC 2068 Section 2.410411 In particular, parse comma-separated lists where the elements of412 the list may include quoted-strings. A quoted-string could
14 unmodified lines
427 :param value: a string with a list header.428 :return: :class:`list`429 :rtype: list430 """388 result = []431 result: list[str] = []432 for item in _parse_list_header(value):433 if item[:1] == item[-1:] == '"':434 item = unquote_header_value(item[1:-1])435 result.append(item)436 return result437438439# From mitsuhiko/werkzeug (used with permission).397def parse_dict_header(value):440def parse_dict_header(value: str) -> dict[str, str | None]:441 """Parse lists of key, value pairs as described by RFC 2068 Section 2 and442 convert them into a python dict:443444 >>> d = parse_dict_header('foo="is a fish", bar="as well"')
13 unmodified lines
458 :param value: a string with a dict header.459 :return: :class:`dict`460 :rtype: dict461 """419 result = {}462 result: dict[str, str | None] = {}463 for item in _parse_list_header(value):464 if "=" not in item:465 result[item] = None466 continue
4 unmodified lines
471 return result472473474# From mitsuhiko/werkzeug (used with permission).432def unquote_header_value(value, is_filename=False):475def unquote_header_value(value: str, is_filename: bool = False) -> str:476 r"""Unquotes a header value. (Reversal of :func:`quote_header_value`).477 This does not use the real unquoting but what browsers are actually478 using for quoting.479
16 unmodified lines
496 return value.replace("\\\\", "\\").replace('\\"', '"')497 return value498499457def dict_from_cookiejar(cj):500def dict_from_cookiejar(cj: CookieJar) -> dict[str, str | None]:501 """Returns a key/value dictionary from a CookieJar.502503 :param cj: CookieJar object to extract cookies from.504 :rtype: dict
2 unmodified lines
507 cookie_dict = {cookie.name: cookie.value for cookie in cj}508 return cookie_dict509510468def add_dict_to_cookiejar(cj, cookie_dict):511def add_dict_to_cookiejar(cj: CookieJar, cookie_dict: dict[str, str]) -> CookieJar:512 """Returns a CookieJar from a key/value dictionary.513514 :param cj: CookieJar to insert cookies into.515 :param cookie_dict: Dict of key/values to insert into CookieJar.
2 unmodified lines
518519 return cookiejar_from_dict(cookie_dict, cj)520521479def get_encodings_from_content(content):522def get_encodings_from_content(content: str) -> list[str]:523 """Returns encodings from given content string.524525 :param content: bytestring to extract encodings from.526 """
16 unmodified lines
543 + xml_re.findall(content)544 )545546504def _parse_content_type_header(header):547def _parse_content_type_header(header: str) -> tuple[str, dict[str, Any]]:548 """Returns content type and parameters from given header.549550 :param header: string551 :return: tuple containing content type and dictionary of
1 unmodified line
553 """554555 tokens = header.split(";")556 content_type, params = tokens[0].strip(), tokens[1:]514 params_dict = {}557 params_dict: dict[str, str | bool] = {}558 strip_chars = "\"' "559560 for param in params:561 param = param.strip()
3 unmodified lines
565 params_dict[key.lower()] = value566 return content_type, params_dict567568526def get_encoding_from_headers(headers):569def get_encoding_from_headers(headers: CaseInsensitiveDict[str]) -> str | None:570 """Returns encodings from given HTTP Header Dict.571572 :param headers: dictionary to extract encoding from.573 :rtype: str
16 unmodified lines
590 # Assume UTF-8 based on RFC 4627: https://www.ietf.org/rfc/rfc4627.txt since the charset was unset591 return "utf-8"592593551def stream_decode_response_unicode(iterator, r):594def stream_decode_response_unicode(595 iterator: Iterable[bytes], r: Response596) -> Generator[str | bytes, None, None]:597 """Stream decodes an iterator."""598599 if r.encoding is None:600 yield from iterator
8 unmodified lines
609 if rv:610 yield rv611612568def iter_slices(string, slice_length):613@overload614def iter_slices(615 string: bytes, slice_length: int | None616) -> Generator[bytes, None, None]: ...617@overload618def iter_slices(619 string: str, slice_length: int | None620) -> Generator[str, None, None]: ...621def iter_slices(622 string: bytes | str, slice_length: int | None623) -> Generator[bytes | str, None, None]:624 """Iterate over slices of a string."""625 pos = 0626 if slice_length is None or slice_length <= 0:627 slice_length = len(string)
1 unmodified line
629 yield string[pos : pos + slice_length]630 pos += slice_length631632578def get_unicode_from_response(r):633def get_unicode_from_response(r: Response) -> str | bytes | None:634 """Returns the requested content back in unicode.635636 :param r: Response object to get unicode content from.637
11 unmodified lines
649 " warning should only appear once.)"650 ),651 DeprecationWarning,652 )653 if r.content is None: # type: ignore[reportUnnecessaryComparison]654 return None655599 tried_encodings = []656 tried_encodings: list[str] = []657658 # Try charset from content-type659 encoding = get_encoding_from_headers(r.headers)660
4 unmodified lines
665 tried_encodings.append(encoding)666667 # Fall back:668 try:612 return str(r.content, encoding, errors="replace")669 return str(r.content, encoding or "utf-8", errors="replace")670 except TypeError:671 return r.content672673674# The unreserved URI characters (RFC 3986)618UNRESERVED_SET = frozenset(675UNRESERVED_SET: Final = frozenset(676 "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz" + "0123456789-._~"677)678679623def unquote_unreserved(uri):680def unquote_unreserved(uri: str) -> str:681 """Un-escape any percent-escape sequences in a URI that are unreserved682 characters. This leaves all reserved, illegal and non-ASCII bytes encoded.683684 :rtype: str
15 unmodified lines
700 parts[i] = f"%{parts[i]}"701 return "".join(parts)702703647def requote_uri(uri):704def requote_uri(uri: str) -> str:705 """Re-quote the given URI.706707 This function passes the given URI through an unquote/quote cycle to708 ensure that it is fully and consistently quoted.
13 unmodified lines
722 # properly quoted so they do not cause issues elsewhere.723 return quote(uri, safe=safe_without_percent)724725669def address_in_network(ip, net):726def address_in_network(ip: str, net: str) -> bool:727 """This function allows you to check if an IP belongs to a network subnet728729 Example: returns True if ip = 192.168.1.1 and net = 192.168.1.0/24730 returns False if ip = 192.168.1.1 and net = 192.168.100.0/24
6 unmodified lines
737 network = struct.unpack("=L", socket.inet_aton(netaddr))[0] & netmask738 return (ipaddr & netmask) == (network & netmask)739740684def dotted_netmask(mask):741def dotted_netmask(mask: int) -> str:742 """Converts mask from /xx format to xxx.xxx.xxx.xxx743744 Example: if mask is 24 function returns 255.255.255.0745
2 unmodified lines
748 bits = 0xFFFFFFFF ^ (1 << 32 - mask) - 1749 return socket.inet_ntoa(struct.pack(">I", bits))750751695def is_ipv4_address(string_ip):752def is_ipv4_address(string_ip: str) -> bool:753 """754 :rtype: bool755 """756 try:
2 unmodified lines
759 return False760 return True761762706def is_valid_cidr(string_network):763def is_valid_cidr(string_network: str) -> bool:764 """765 Very simple check of the cidr format in no_proxy variable.766767 :rtype: bool
16 unmodified lines
784 return True785786787@contextlib.contextmanager731def set_environ(env_name, value):788def set_environ(env_name: str, value: str | None) -> Generator[None, None, None]:789 """Set the environment variable 'env_name' to 'value'790791 Save previous value, yield, and then restore the previous value stored in792 the environment variable 'env_name'.793794 If 'value' is None, do nothing"""795 value_changed = value is not None796 old_value: str | None = None797 if value_changed:798 old_value = os.environ.get(env_name)799 os.environ[env_name] = value800 try:
5 unmodified lines
806 else:807 os.environ[env_name] = old_value808809752def should_bypass_proxies(url, no_proxy):810def should_bypass_proxies(url: str, no_proxy: str | None) -> bool:811 """812 Returns whether we should bypass proxies or not.813814 :rtype: bool815 """816817 # Prioritize lowercase environment variables over uppercase818 # to keep a consistent behaviour with other http projects (curl, wget).761 def get_proxy(key):819 def get_proxy(key: str) -> str | None:820 return os.environ.get(key) or os.environ.get(key.upper())821822 # First check whether no_proxy is defined. If it is, check that the URL823 # we're getting isn't in the no_proxy list.824 no_proxy_arg = no_proxy825 if no_proxy is None:826 no_proxy = get_proxy("no_proxy")827 parsed = urlparse(url)828 hostname = parsed.hostname829771 if parsed.hostname is None:830 if hostname is None:831 # URLs don't always have hostnames, e.g. file:/// urls.832 return True833834 if no_proxy:835 # We need to check whether we match here. We need to see if we match836 # the end of the hostname, both with and without the port.778 no_proxy = (host for host in no_proxy.replace(" ", "").split(",") if host)837 no_proxy_hosts = (host for host in no_proxy.replace(" ", "").split(",") if host)838780 if is_ipv4_address(parsed.hostname):781 for proxy_ip in no_proxy:839 if is_ipv4_address(hostname):840 for proxy_ip in no_proxy_hosts:841 if is_valid_cidr(proxy_ip):783 if address_in_network(parsed.hostname, proxy_ip):842 if address_in_network(hostname, proxy_ip):843 return True785 elif parsed.hostname == proxy_ip:844 elif hostname == proxy_ip:845 # If no_proxy ip was defined in plain IP notation instead of cidr notation &846 # matches the IP of the index847 return True848 else:790 host_with_port = parsed.hostname849 host_with_port = hostname850 if parsed.port:851 host_with_port += f":{parsed.port}"852794 for host in no_proxy:795 if parsed.hostname.endswith(host) or host_with_port.endswith(host):853 for host in no_proxy_hosts:854 if hostname.endswith(host) or host_with_port.endswith(host):855 # The URL does match something in no_proxy, so we don't want856 # to apply the proxies on this URL.857 return True858859 with set_environ("no_proxy", no_proxy_arg):801 # parsed.hostname can be `None` in cases such as a file URI.860 try:803 bypass = proxy_bypass(parsed.hostname)861 bypass = proxy_bypass(hostname)862 except (TypeError, socket.gaierror):863 bypass = False864865 if bypass:
1 unmodified line
867868 return False869870813def get_environ_proxies(url, no_proxy=None):871def get_environ_proxies(url: str, no_proxy: str | None = None) -> dict[str, str]:872 """873 Return a dict of environment proxies.874875 :rtype: dict
3 unmodified lines
879 else:880 return getproxies()881882825def select_proxy(url, proxies):883def select_proxy(url: str, proxies: dict[str, str] | None) -> str | None:884 """Select a proxy for the url, if applicable.885886 :param url: The url being for the request887 :param proxies: A dictionary of schemes or schemes and hosts to proxy URLs
17 unmodified lines
905906 return proxy907908851def resolve_proxies(request, proxies, trust_env=True):909def resolve_proxies(910 request: Request | PreparedRequest,911 proxies: dict[str, str] | None,912 trust_env: bool = True,913) -> dict[str, str]:914 """This method takes proxy information from a request and configuration915 input to resolve a mapping of target proxies. This will consider settings916 such as NO_PROXY to strip proxy configurations.917
3 unmodified lines
921922 :rtype: dict923 """924 proxies = proxies if proxies is not None else {}863 url = request.url925 url = cast(str, request.url)926 scheme = urlparse(url).scheme927 no_proxy = proxies.get("no_proxy")928 new_proxies = proxies.copy()929
6 unmodified lines
936 new_proxies.setdefault(scheme, proxy)937 return new_proxies938939878def default_user_agent(name="python-requests"):940def default_user_agent(name: str = "python-requests") -> str:941 """942 Return a string representing the default user agent.943944 :rtype: str945 """946 return f"{name}/{__version__}"947948887def default_headers():949def default_headers() -> CaseInsensitiveDict[str]:950 """951 :rtype: requests.structures.CaseInsensitiveDict952 """953 return CaseInsensitiveDict(
5 unmodified lines
959 }960 )961962901def parse_header_links(value):963def parse_header_links(value: str) -> list[dict[str, str]]:964 """Return a list of parsed link headers proxies.965966 i.e. Link: <http:/.../front.jpeg>; rel=front; type="image/jpeg",<http://.../back.jpeg>; rel=back;type="image/jpeg"967968 :rtype: list969 """970909 links = []971 links: list[dict[str, str]] = []972973 replace_chars = " '\""974975 value = value.strip(replace_chars)
5 unmodified lines
981 url, params = val.split(";", 1)982 except ValueError:983 url, params = val, ""984923 link = {"url": url.strip("<> '\"")}985 link: dict[str, str] = {"url": url.strip("<> '\"")}986987 for param in params.split(";"):988 try:989 key, value = param.split("=")
12 unmodified lines
1002_null2 = _null * 21003_null3 = _null * 310041005944def guess_json_utf(data):1006def guess_json_utf(data: bytes) -> str | None:1007 """1008 :rtype: str1009 """1010 # JSON always starts with two ASCII characters, so detection is as
23 unmodified lines
1034 # Did not detect a valid UTF-32 ascii-range character1035 return None10361037976def prepend_scheme_if_needed(url, new_scheme):1038def prepend_scheme_if_needed(url: str, new_scheme: str) -> str:1039 """Given a URL that may or may not have a scheme, prepend the given scheme.1040 Does not replace a present scheme with the one provided as an argument.10411042 :rtype: str1043 """1044 parsed = parse_url(url)983 scheme, auth, host, port, path, query, fragment = parsed1045 scheme, auth, _host, _port, path, query, fragment = parsed10461047 # A defect in urlparse determines that there isn't a netloc present in some1048 # urls. We previously assumed parsing was overly cautious, and swapped the1049 # netloc and path. Due to a lack of tests on the original defect, this is
4 unmodified lines
10541055 if auth:1056 # parse_url doesn't provide the netloc with auth1057 # so we'll add it ourselves.1058 netloc = cast(str, netloc)1059 netloc = "@".join([auth, netloc])1060 if scheme is None:1061 scheme = new_scheme1062 if path is None:
1 unmodified line
10641065 return urlunparse((scheme, netloc, path, "", query, fragment))106610671005def get_auth_from_url(url):1068def get_auth_from_url(url: str) -> tuple[str, str]:1069 """Given a url with authentication components, extract them into a tuple of1070 username,password.10711072 :rtype: (str,str)1073 """1074 parsed = urlparse(url)10751076 try:1077 # except handles parsed.username/password being None1014 auth = (unquote(parsed.username), unquote(parsed.password))1078 auth = (unquote(parsed.username), unquote(parsed.password)) # type: ignore[arg-type]1079 except (AttributeError, TypeError):1080 auth = ("", "")10811082 return auth108310841021def check_header_validity(header):1085def check_header_validity(header: tuple[str | bytes, str | bytes]) -> None:1086 """Verifies that header parts don't contain leading whitespace1087 reserved characters, or return characters.10881089 :param header: tuple, in the format (name, value).
2 unmodified lines
1092 _validate_header_part(header, name, 0)1093 _validate_header_part(header, value, 1)109410951032def _validate_header_part(header, header_part, header_validator_index):1096def _validate_header_part(1097 header: tuple[str | bytes, str | bytes],1098 header_part: str | bytes,1099 header_validator_index: int,1100) -> None:1101 if isinstance(header_part, str):1102 validator = _HEADER_VALIDATORS_STR[header_validator_index]1035 elif isinstance(header_part, bytes):1103 elif isinstance(header_part, bytes): # type: ignore[reportUnnecessaryIsInstance]1104 # runtime guard for non-str/bytes input1105 validator = _HEADER_VALIDATORS_BYTE[header_validator_index]1106 else:1107 raise InvalidHeader(1108 f"Header part ({header_part!r}) from {header} "1109 f"must be of type str or bytes, not {type(header_part)}"1110 )11111043 if not validator.match(header_part):1112 if not validator.match(header_part): # type: ignore[arg-type]1113 header_kind = "name" if header_validator_index == 0 else "value"1114 raise InvalidHeader(1115 f"Invalid leading whitespace, reserved character(s), or return "1116 f"character(s) in header {header_kind}: {header_part!r}"1117 )111811191051def urldefragauth(url):1120def urldefragauth(url: str) -> str:1121 """1122 Given a url remove the fragment and the authentication part.11231124 :rtype: str1125 """1057 scheme, netloc, path, params, query, fragment = urlparse(url)1126 scheme, netloc, path, params, query, _fragment = urlparse(url)11271128 # see func:`prepend_scheme_if_needed`1129 if not netloc:1130 netloc, path = path, netloc
2 unmodified lines
11331134 return urlunparse((scheme, netloc, path, params, query, ""))113511361068def rewind_body(prepared_request):1137def rewind_body(prepared_request: PreparedRequest) -> None:1138 """Move file pointer back to its recorded starting position1139 so it can be read again on redirect.1140 """1141 body_seek = getattr(prepared_request.body, "seek", None)1142 if body_seek is not None and isinstance(1074 prepared_request._body_position, integer_types1143 prepared_request._body_position, # type: ignore[reportPrivateUsage]1144 integer_types,1145 ):1146 try:1077 body_seek(prepared_request._body_position)1147 body_seek(prepared_request._body_position) # type: ignore[reportPrivateUsage]1148 except OSError:1149 raise UnrewindableBodyError(1150 "An error occurred when rewinding request body for redirect."1151 )
2 unmodified lines
modified:tests/test_requests.py+1 added
2577 unmodified lines
25782579 def build_response(self):2580 request = self.calls[-1].args[0]2581 r = requests.Response()2582 r.url = request.url25832584 try:2585 r.status_code = int(self.redirects.pop(0))2586 except IndexError:
467 unmodified lines
modified:pyproject.toml+9 added
62 unmodified lines
63 "pytest-xdist",64 "pytest>=3",65 "trustme",66]67typecheck = [68 "pyright",69 "typing_extensions",70]7172[tool.setuptools]73license-files = ["LICENSE", "NOTICE"]74
32 unmodified lines
107addopts = "--doctest-modules"108doctest_optionflags = "NORMALIZE_WHITESPACE ELLIPSIS"109minversion = "6.2"110testpaths = ["tests"]111112113[tool.pyright]114include = ["src/requests"]115typeCheckingMode = "strict"