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
Provenance
- Commit
561e4b6- Tree
dbd62ba- Author
Nate Prewitt <nate.prewitt@gmail.com>- Committer
GitHub <noreply@github.com>- Parent
8f6cda9
20 files changed+1308 added−525 removed
added:.github/workflows/typecheck.yml+32 added
1234567891011121314151617181920212223242526272829303132name: Type Check
on: [push, pull_request]
permissions: contents: read
jobs: typecheck: runs-on: ubuntu-24.04 timeout-minutes: 10 strategy: matrix: python-version: ["3.10", "3.14"]
steps: - uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2 with: persist-credentials: false
- name: Set up Python uses: actions/setup-python@a309ff8b426b58ec0e2a45f0f869d46889d02405 # v6.2.0 with: python-version: ${{ matrix.python-version }}
- name: Install dependencies run: | python -m pip install pip==26.0.1 python -m pip install -e . --group typecheck
- name: Run pyright run: python -m pyright src/requests/modified:src/requests/__init__.py+53 added-17 removed
36 unmodified lines37 :copyright: (c) 2017 by Kenneth Reitz.38 :license: Apache 2.0, see LICENSE for more details.39 """40 41+from __future__ import annotations42+43 import warnings44 45 import urllib346 4 unmodified lines51 except ImportError:52 charset_normalizer_version = None53 54 try:53- from chardet import __version__ as chardet_version55+ from chardet import __version__ as chardet_version # type: ignore[import-not-found]56 except ImportError:57 chardet_version = None58 59 58-def 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.60+def 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.67 68 # 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")71 72 # 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 lines95 RequestsDependencyWarning,96 )97 98 93-def _check_cryptography(cryptography_version):99+def _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 return105 100- 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)109 110 111 # Check imported dependencies for compatibility.112 try: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 )118 except (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 lines137 138 pyopenssl.inject_into_urllib3()139 140 # 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+ )144 137- _check_cryptography(cryptography_version)145+ _check_cryptography(cryptography_version) # type: ignore[reportUnknownArgumentType]146 except ImportError:147 pass148 149 # urllib3's DependencyWarnings should be silenced.34 unmodified lines184 from .models import PreparedRequest, Request, Response185 from .sessions import Session, session186 from .status_codes import codes187 188+__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+)215+216 logging.getLogger(__name__).addHandler(NullHandler())217 218 # FileModeWarnings go off per the default.219 warnings.simplefilter("default", FileModeWarning, append=True)modified:src/requests/_internal_utils.py+2 added-2 removed
21 unmodified lines22 str: _HEADER_VALIDATORS_STR,23 }24 25 26-def to_native_string(string, encoding="ascii"):26+def 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 lines35 36 return out37 38 39-def unicode_is_ascii(u_string):39+def unicode_is_ascii(u_string: str) -> bool:40 """Determine if unicode string only contains ASCII characters.41 42 :param str u_string: unicode string to check. Must be unicode43 and not Python 2 `str`.8 unmodified linesadded:src/requests/_types.py+176 added
1+"""2+requests._types3+~~~~~~~~~~~~~~~4+5+This module contains type aliases used internally by the Requests library.6+These types are not part of the public API and must not be relied upon7+by external code.8+"""9+10+from __future__ import annotations11+12+from collections.abc import Callable, Iterable, Mapping, MutableMapping13+from typing import (14+ TYPE_CHECKING,15+ Any,16+ Protocol,17+ TypeAlias,18+ TypeVar,19+ runtime_checkable,20+)21+22+_T_co = TypeVar("_T_co", covariant=True)23+24+25+@runtime_checkable26+class SupportsRead(Protocol[_T_co]):27+ def read(self, length: int = ..., /) -> _T_co: ...28+29+30+@runtime_checkable31+class SupportsItems(Protocol):32+ def items(self) -> Iterable[tuple[Any, Any]]: ...33+34+35+# These are needed at runtime for default_hooks() return type36+HookType: TypeAlias = Callable[["Response"], Any]37+HooksInputType: TypeAlias = Mapping[str, Iterable[HookType] | HookType]38+39+40+def 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 True46+47+48+if TYPE_CHECKING:49+ from http.cookiejar import CookieJar50+ from typing import TypeAlias, TypedDict51+52+ from typing_extensions import (53+ Buffer, # TODO: move to collections.abc when Python >= 3.1254+ TypeIs, # TODO: move to typing when Python >= 3.1355+ )56+57+ from .auth import AuthBase58+ from .cookies import RequestsCookieJar59+ from .models import PreparedRequest, Response60+ from .structures import CaseInsensitiveDict61+62+ class _ValidatedRequest(PreparedRequest):63+ """Subtype asserting a PreparedRequest has been fully prepared before calling.64+65+ 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+ """70+71+ url: str # type: ignore[reportIncompatibleVariableOverride]72+ method: str # type: ignore[reportIncompatibleVariableOverride]73+74+ # Type aliases for core API concepts (ordered by request() signature)75+ UriType: TypeAlias = str | bytes76+77+ _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+ )89+90+ KVDataType: TypeAlias = Iterable[tuple[Any, Any]] | Mapping[Any, Any]91+92+ RawDataType: TypeAlias = KVDataType | str | bytes93+ StreamDataType: TypeAlias = SupportsRead[str | bytes]94+ EncodableDataType: TypeAlias = RawDataType | StreamDataType95+96+ DataType: TypeAlias = (97+ KVDataType98+ | Iterable[bytes | str]99+ | str100+ | bytes101+ | Buffer102+ | SupportsRead[str | bytes]103+ | None104+ )105+106+ BodyType: TypeAlias = (107+ bytes | str | Iterable[bytes | str] | SupportsRead[bytes | str] | None108+ )109+110+ HeadersType: TypeAlias = CaseInsensitiveDict[str] | Mapping[str, str | bytes]111+ HeadersUpdateType: TypeAlias = Mapping[str, str | bytes | None]112+113+ CookiesType: TypeAlias = RequestsCookieJar | Mapping[str, str]114+115+ # 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+ )129+130+ AuthType: TypeAlias = (131+ tuple[str, str] | AuthBase | Callable[[PreparedRequest], PreparedRequest] | None132+ )133+134+ 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+ )142+143+ # TypedDicts for Unpack kwargs (PEP 692)144+145+ 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: CertType157+158+ class RequestKwargs(BaseRequestKwargs, total=False):159+ """kwargs for request(), options(), head(), delete()."""160+161+ params: ParamsType162+ data: DataType163+ json: JsonType164+165+ class GetKwargs(BaseRequestKwargs, total=False):166+ data: DataType167+ json: JsonType168+169+ class PostKwargs(BaseRequestKwargs, total=False):170+ params: ParamsType171+172+ class DataKwargs(BaseRequestKwargs, total=False):173+ """kwargs for put(), patch()."""174+175+ params: ParamsType176+ json: JsonTypemodified:src/requests/adapters.py+100 added-47 removed
4 unmodified lines5 This module contains the transport adapters that Requests uses to define6 and maintain connections.7 """8 9+from __future__ import annotations10+11 import os.path10-import socket # noqa: F40112+import socket # noqa: F401 # type: ignore[reportUnusedImport]13 import typing14 import warnings15+from typing import Any16 17 from urllib3.exceptions import (18 ClosedPoolError,19 ConnectTimeoutError,12 unmodified lines32 from urllib3.util import Timeout as TimeoutSauce33 from urllib3.util import parse_url34 from urllib3.util.retry import Retry35 33-from .auth import _basic_auth_str36+from .auth import _basic_auth_str # type: ignore[reportPrivateUsage]37 from .compat import basestring, urlparse38 from .cookies import extract_cookies_to_jar39 from .exceptions import (40 ConnectionError,18 unmodified lines59 urldefragauth,60 )61 62 try:60- from urllib3.contrib.socks import SOCKSProxyManager63+ from urllib3.contrib.socks import SOCKSProxyManager # type: ignore[assignment]64 except ImportError:65 63- def SOCKSProxyManager(*args, **kwargs):66+ def SOCKSProxyManager(*args: Any, **kwargs: Any) -> None:67 raise InvalidSchema("Missing dependencies for SOCKS support.")68 69 70 if typing.TYPE_CHECKING:71+ from urllib3.connectionpool import HTTPConnectionPool72+ from urllib3.poolmanager import PoolManager as _PoolManager73+74+ from . import _types as _t75 from .models import PreparedRequest76 77+from ._types import is_prepared as _is_prepared78 79 DEFAULT_POOLBLOCK = False80 DEFAULT_POOLSIZE = 1081 DEFAULT_RETRIES = 082 DEFAULT_POOL_TIMEOUT = None83 84 85 def _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 lines121 122 class BaseAdapter:123 """The Base Transport Adapter"""124 117- def __init__(self):125+ def __init__(self) -> None:126 super().__init__()127 128 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.138 139 :param request: The :class:`PreparedRequest <PreparedRequest>` being sent.140 :param stream: (optional) Whether to stream the request content.8 unmodified lines149 :param proxies: (optional) The proxies dictionary to apply to the request.150 """151 raise NotImplementedError152 139- def close(self):153+ def close(self) -> None:154 """Cleans up adapter specific items."""155 raise NotImplementedError156 157 23 unmodified lines181 >>> a = requests.adapters.HTTPAdapter(max_retries=3)182 >>> s.mount('http://', a)183 """184 171- __attrs__ = [185+ __attrs__: list[str] = [186 "max_retries",187 "config",188 "_pool_connections",189 "_pool_maxsize",190 "_pool_block",191 ]192 193+ max_retries: Retry194+ config: dict[str, Any]195+ proxy_manager: dict[str, Any]196+ _pool_connections: int197+ _pool_maxsize: int198+ _pool_block: bool199+ poolmanager: _PoolManager200+201 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 lines219 self._pool_block = pool_block220 221 self.init_poolmanager(pool_connections, pool_maxsize, block=pool_block)222 201- def __getstate__(self):223+ def __getstate__(self) -> dict[str, Any]:224 return {attr: getattr(self, attr, None) for attr in self.__attrs__}225 204- 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 lines236 self._pool_connections, self._pool_maxsize, block=self._pool_block237 )238 239 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.247 248 This method should not be called from user code, and is only249 exposed for use when subclassing the15 unmodified lines265 block=block,266 **pool_kwargs,267 )268 243- 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.271 272 This method should not be called from user code, and is only273 exposed for use when subclassing the29 unmodified lines303 )304 305 return manager306 281- 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 lines361 raise OSError(362 f"Could not find the TLS key file, invalid path: {conn.key_file}"363 )364 337- 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 line371 :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()377 378 # 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]380 381 # Make headers case-insensitive.382 response.headers = CaseInsensitiveDict(getattr(resp, "headers", {}))383 15 unmodified lines399 response.connection = self400 401 return response402 374- 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.407 408 This looks at the PreparedRequest, the user-specified verify value,409 and the value of the cert parameter to determine what PoolKey values41 unmodified lines451 second is a dictionary of SSLContext related parameters.452 """453 return _urllib3_request_context(request, verify, cert, self.poolmanager)454 424- 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 lines475 :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)482+483 proxy = select_proxy(request.url, proxies)484 try:485 host_params, pool_kwargs = self.build_connection_pool_key_attributes(486 request,21 unmodified lines508 )509 510 return conn511 473- 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.517 518 Returns a urllib3 connection for the given URL. This should not be1 unmodified line520 :class:`HTTPAdapter <requests.adapters.HTTPAdapter>`.521 522 :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 lines551 conn = self.poolmanager.connection_from_url(url)552 553 return conn554 514- def close(self):555+ def close(self) -> None:556 """Disposes of any internal state.557 558 Currently, this closes the PoolManager and any active ProxyManager,559 which closes any pooled connections.1 unmodified line561 self.poolmanager.clear()562 for proxy in self.proxy_manager.values():563 proxy.clear()564 524- 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.569 570 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 lines577 :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)582+583 proxy = select_proxy(request.url, proxies)584 scheme = urlparse(request.url).scheme585 586 is_proxied_http_request = proxy and scheme != "https"10 unmodified lines597 url = urldefragauth(request.url)598 599 return url600 556- 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 lines611 :param kwargs: The keyword arguments from the call to send().612 """613 pass614 570- 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 lines624 625 :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)630 631 if username:632 headers["Proxy-Authorization"] = _basic_auth_str(username, password)633 634 return headers635 636 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.646 647 :param request: The :class:`PreparedRequest <PreparedRequest>` being sent.648 :param stream: (optional) Whether to stream the request content.8 unmodified lines657 :param proxies: (optional) The proxies dictionary to apply to the request.658 :rtype: requests.Response659 """660 661+ assert _is_prepared(request)662+663 try:664 conn = self.get_connection_with_tls_context(665 request, verify, proxies=proxies, cert=cert666 )15 unmodified lines682 683 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)696 697 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 )711 712 except (ProtocolError, OSError) as err:38 unmodified linesmodified:src/requests/api.py+31 added-8 removed
6 unmodified lines7 :copyright: (c) 2012 by Kenneth Reitz.8 :license: Apache2, see LICENSE for more details.9 """10 11+from __future__ import annotations12+13+from typing import TYPE_CHECKING14+15 from . import sessions16+from .models import Response17 18+if TYPE_CHECKING:19+ from typing_extensions import Unpack20 14-def request(method, url, **kwargs):21+ from . import _types as _t22+23+24+def request(25+ method: str, url: _t.UriType, **kwargs: Unpack[_t.RequestKwargs]26+) -> Response:27 """Constructs and sends a :class:`Request <Request>`.28 29 :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 lines70 with sessions.Session() as session:71 return session.request(method=method, url=url, **kwargs)72 73 62-def get(url, params=None, **kwargs):74+def get(75+ url: _t.UriType, params: _t.ParamsType = None, **kwargs: Unpack[_t.GetKwargs]76+) -> Response:77 r"""Sends a GET request.78 79 :param url: URL for the new :class:`Request` object.80 :param params: (optional) Dictionary, list of tuples or bytes to send5 unmodified lines86 87 return request("get", url, params=params, **kwargs)88 89 76-def options(url, **kwargs):90+def options(url: _t.UriType, **kwargs: Unpack[_t.RequestKwargs]) -> Response:91 r"""Sends an OPTIONS request.92 93 :param url: URL for the new :class:`Request` object.94 :param \*\*kwargs: Optional arguments that ``request`` takes.3 unmodified lines98 99 return request("options", url, **kwargs)100 101 88-def head(url, **kwargs):102+def head(url: _t.UriType, **kwargs: Unpack[_t.RequestKwargs]) -> Response:103 r"""Sends a HEAD request.104 105 :param url: URL for the new :class:`Request` object.106 :param \*\*kwargs: Optional arguments that ``request`` takes. If6 unmodified lines113 kwargs.setdefault("allow_redirects", False)114 return request("head", url, **kwargs)115 116 103-def post(url, data=None, json=None, **kwargs):117+def 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.124 125 :param url: URL for the new :class:`Request` object.126 :param data: (optional) Dictionary, list of tuples, bytes, or file-like6 unmodified lines133 134 return request("post", url, data=data, json=json, **kwargs)135 136 118-def put(url, data=None, **kwargs):137+def put(138+ url: _t.UriType, data: _t.DataType = None, **kwargs: Unpack[_t.DataKwargs]139+) -> Response:140 r"""Sends a PUT request.141 142 :param url: URL for the new :class:`Request` object.143 :param data: (optional) Dictionary, list of tuples, bytes, or file-like6 unmodified lines150 151 return request("put", url, data=data, **kwargs)152 153 133-def patch(url, data=None, **kwargs):154+def patch(155+ url: _t.UriType, data: _t.DataType = None, **kwargs: Unpack[_t.DataKwargs]156+) -> Response:157 r"""Sends a PATCH request.158 159 :param url: URL for the new :class:`Request` object.160 :param data: (optional) Dictionary, list of tuples, bytes, or file-like6 unmodified lines167 168 return request("patch", url, data=data, **kwargs)169 170 148-def delete(url, **kwargs):171+def delete(url: _t.UriType, **kwargs: Unpack[_t.RequestKwargs]) -> Response:172 r"""Sends a DELETE request.173 174 :param url: URL for the new :class:`Request` object.175 :param \*\*kwargs: Optional arguments that ``request`` takes.5 unmodified linesmodified:src/requests/auth.py+75 added-35 removed
3 unmodified lines4 5 This module contains the authentication handlers for Requests.6 """7 8+from __future__ import annotations9+10 import hashlib11 import os12 import re13 import threading14 import time15 import warnings16 from base64 import b64encode17+from typing import TYPE_CHECKING, Any, Final, cast, overload18 19 from ._internal_utils import to_native_string20 from .compat import basestring, str, urlparse21 from .cookies import extract_cookies_to_jar22 from .utils import parse_dict_header23 21-CONTENT_TYPE_FORM_URLENCODED = "application/x-www-form-urlencoded"22-CONTENT_TYPE_MULTI_PART = "multipart/form-data"24+if TYPE_CHECKING:25+ from http.cookiejar import CookieJar26+ from typing import Any27 28+ from .models import PreparedRequest, Response29 25-def _basic_auth_str(username, password):30+CONTENT_TYPE_FORM_URLENCODED: Final = "application/x-www-form-urlencoded"31+CONTENT_TYPE_MULTI_PART: Final = "multipart/form-data"32+33+34+def _basic_auth_str(username: bytes | str, password: bytes | str) -> str:35 """Returns a Basic Auth string."""36 37 # "I want us to put a big-ol' comment on top of it that38 # says that this behaviour is dumb but we need to preserve1 unmodified line40 # - 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 line50 category=DeprecationWarning,51 )52 username = str(username)53 45- 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 lines77 78 class AuthBase:79 """Base class that all auth implementations derive from"""80 72- def __call__(self, r):81+ def __call__(self, r: PreparedRequest) -> PreparedRequest:82 raise NotImplementedError("Auth hooks must be callable.")83 84 85 class HTTPBasicAuth(AuthBase):86 """Attaches HTTP Basic Authentication to the given Request object."""87 79- def __init__(self, username, password):88+ username: bytes | str89+ password: bytes | str90+91+ @overload92+ def __init__(self, username: str, password: str) -> None: ...93+ @overload94+ def __init__(self, username: bytes, password: bytes) -> None: ...95+96+ def __init__(self, username: bytes | str, password: bytes | str) -> None:97 self.username = username98 self.password = password99 83- 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 )107 91- def __ne__(self, other):108+ def __ne__(self, other: Any) -> bool:109 return not self == other110 94- def __call__(self, r):111+ def __call__(self, r: PreparedRequest) -> PreparedRequest:112 r.headers["Authorization"] = _basic_auth_str(self.username, self.password)113 return r114 115 116 class HTTPProxyAuth(HTTPBasicAuth):117 """Attaches HTTP Proxy Authentication to a given Request object."""118 102- 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 r122 123 124 class HTTPDigestAuth(AuthBase):125 """Attaches HTTP Digest Authentication to the given Request object."""126 110- 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 | None135+136+ @overload137+ def __init__(self, username: str, password: str) -> None: ...138+ @overload139+ def __init__(self, username: bytes, password: bytes) -> None: ...140+141+ 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()146 116- 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 line153 self._thread_local.chal = {}154 self._thread_local.pos = None155 self._thread_local.num_401_calls = None156 126- 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 lines172 _algorithm = algorithm.upper()173 # lambdas assume digest modules are imported at the top level174 if _algorithm == "MD5" or _algorithm == "MD5-SESS":175 145- 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()180 181 hash_utf8 = md5_utf8182 elif _algorithm == "SHA":183 153- 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()188 189 hash_utf8 = sha_utf8190 elif _algorithm == "SHA-256":191 161- 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()196 197 hash_utf8 = sha256_utf8198 elif _algorithm == "SHA-512":199 169- 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()204 205 hash_utf8 = sha512_utf8206 176- KD = lambda s, d: hash_utf8(f"{s}:{d}") # noqa:E731177-207 if hash_utf8 is None:208 return None209 210+ def KD(s: str, d: str) -> str:211+ return hash_utf8(f"{s}:{d}")212+213 # XXX not implemented yet214 entdig = None215 p_parsed = urlparse(url)216 #: path is request-uri defined in RFC 2616 which should not be empty18 unmodified lines235 s += os.urandom(8)236 237 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 terminology240 241 if not qop:242 respdig = KD(HA1, f"{nonce}:{HA2}")243 elif qop == "auth" or "auth" in qop.split(","):20 unmodified lines264 base += f', qop="auth", nc={ncvalue}, cnonce="{cnonce}"'265 266 return f"Digest {base}"267 236- 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 = 1272 241- 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.276 277 :rtype: requests.Response7 unmodified lines285 286 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", "")292 293 if "digest" in s_auth.lower() and self._thread_local.num_401_calls < 2:294 self._thread_local.num_401_calls += 14 unmodified lines299 # 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)306 273- 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 line317 318 self._thread_local.num_401_calls = 1319 return r320 285- 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 lines341 self._thread_local.num_401_calls = 1342 343 return r344 305- 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 )352 313- def __ne__(self, other):353+ def __ne__(self, other: Any) -> bool:354 return not self == othermodified:src/requests/compat.py+12 added-5 removed
5 unmodified lines6 between Python 2 and Python 3. It remains for backwards7 compatibility until the next major version.8 """9 10+# pyright: reportUnusedImport=false11+12+from __future__ import annotations13+14 import importlib15 import sys16+from types import ModuleType17 18 # -------19 # urllib320 # -------16-from urllib3 import __version__ as urllib3_version21+from urllib3 import (22+ __version__ as urllib3_version, # type: ignore[reportPrivateImportUsage]23+)24 25 # Detect which major version of urllib3 is being used.26 try:27 is_urllib3_1 = int(urllib3_version.split(".")[0]) == 15 unmodified lines33 # Character Detection34 # -------------------35 36 30-def _resolve_char_detection():37+def _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 lines63 64 # json/simplejson module import resolution65 has_simplejson = False66 try:60- import simplejson as json67+ import simplejson as json # type: ignore[import-not-found]68 69 has_simplejson = True70 except ImportError:71 import json72 73 if has_simplejson:67- from simplejson import JSONDecodeError74+ from simplejson import JSONDecodeError # type: ignore[import-not-found]75 else:76 from json import JSONDecodeError77 78 # Keep OrderedDict for backwards compatibility.22 unmodified lines101 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 )107 108 builtin_str = str109 str = str4 unmodified linesmodified:src/requests/cookies.py+143 added-79 removed
5 unmodified lines6 7 requests.utils imports from here, so be careful with imports.8 """9 10+from __future__ import annotations11+12 import calendar13 import copy14 import time15+from collections.abc import Iterator, MutableMapping16+from http.cookiejar import Cookie, CookieJar, CookiePolicy17+from typing import TYPE_CHECKING, Any, TypeVar, overload18 19 from ._internal_utils import to_native_string20+from ._types import is_prepared as _is_prepared15-from .compat import Morsel, MutableMapping, cookielib, urlparse, urlunparse21+from .compat import Morsel, cookielib, urlparse, urlunparse22 17-try:18- import threading19-except ImportError:20- import dummy_threading as threading23+if TYPE_CHECKING:24+ from _typeshed import SupportsKeysAndGetItem25 26+ from .models import PreparedRequest27 28+import threading29+30+31 class MockRequest:24- """Wraps a `requests.Request` to mimic a `urllib2.Request`.32+ """Wraps a `requests.PreparedRequest` to mimic a `urllib2.Request`.33 34 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 lines39 the new headers via `get_new_headers()` and interpreting them appropriately. You40 probably want `get_cookie_header`, defined below.41 """42 43+ type: str44+35- 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).scheme50 40- def get_type(self):51+ def get_type(self) -> str:52 return self.type53 43- def get_host(self):54+ def get_host(self) -> str:55 return urlparse(self._r.url).netloc56 46- def get_origin_req_host(self):57+ def get_origin_req_host(self) -> str:58 return self.get_host()59 49- 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.url11 unmodified lines76 parsed.fragment,77 ]78 )79 69- def is_unverifiable(self):80+ def is_unverifiable(self) -> bool:81 return True82 72- 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_headers85 75- 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]88 78- 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 )94 84- def add_unredirected_header(self, name, value):95+ def add_unredirected_header(self, name: str, value: str) -> None:96 self._new_headers[name] = value97 87- def get_new_headers(self):98+ def get_new_headers(self) -> dict[str, str]:99 return self._new_headers100 101 @property91- def unverifiable(self):102+ def unverifiable(self) -> bool:103 return self.is_unverifiable()104 105 @property95- def origin_req_host(self):106+ def origin_req_host(self) -> str:107 return self.get_origin_req_host()108 109 @property99- def host(self):110+ def host(self) -> str:111 return self.get_host()112 113 114 class MockResponse:2 unmodified lines117 ...what? Basically, expose the parsed HTTP headers from the server response118 the way `http.cookiejar` expects to see them.119 """120 110- def __init__(self, headers):121+ def __init__(self, headers: Any) -> None:122 """Make a MockResponse for `cookiejar` to read.123 124 :param headers: a httplib.HTTPMessage or analogous carrying the headers125 """126 self._headers = headers127 117- def info(self):128+ def info(self) -> Any:129 return self._headers130 120- def getheaders(self, name):131+ def getheaders(self, name: str) -> Any:132 self._headers.getheaders(name)133 134 124-def extract_cookies_to_jar(jar, request, response):135+def extract_cookies_to_jar(136+ jar: CookieJar, request: PreparedRequest, response: Any137+) -> None:138 """Extract the cookies from the response into a CookieJar.139 140 :param jar: http.cookiejar.CookieJar (not necessarily a RequestsCookieJar)141 :param request: our own requests.Request object4 unmodified lines146 # 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]151 152 140-def get_cookie_header(jar, request):153+def get_cookie_header(jar: CookieJar, request: PreparedRequest) -> str | None:154 """155 Produce an appropriate Cookie header string to be sent with `request`, or None.156 157 :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")162 163 151-def remove_cookie_by_name(cookiejar, name, domain=None, path=None):164+def 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.168 169 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 lines187 Use .get and .set and include domain and path args in order to be more specific.188 """189 190 176-class RequestsCookieJar(cookielib.CookieJar, MutableMapping):191+class RequestsCookieJar(CookieJar, MutableMapping[str, str | None]): # type: ignore[misc]192 """Compatibility class; is a http.cookiejar.CookieJar, but exposes a dict193 interface.194 195 This is the CookieJar we create by default for requests and sessions that9 unmodified lines205 206 .. warning:: dictionary operations that are normally O(1) may be O(n).207 """208 194- def get(self, name, default=None, domain=None, path=None):209+ _policy: CookiePolicy210+211+ 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 lines225 return self._find_no_duplicates(name, domain, path)226 except KeyError:227 return default228 206- 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 lines246 c = create_cookie(name, value, **kwargs)247 self.set_cookie(c)248 return c249 225- def iterkeys(self):250+ def iterkeys(self) -> Iterator[str]:251 """Dict-like iterkeys() that returns an iterator of names of cookies252 from the jar.253 254 .. seealso:: itervalues() and iteritems().255 """256 for cookie in iter(self):257 yield cookie.name258 234- 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.262 263 .. seealso:: values() and items().264 """265 return list(self.iterkeys())266 242- 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.270 271 .. seealso:: iterkeys() and iteritems().272 """273 for cookie in iter(self):274 yield cookie.value275 251- 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.279 280 .. seealso:: keys() and items().281 """282 return list(self.itervalues())283 259- 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.287 288 .. seealso:: iterkeys() and itervalues().289 """290 for cookie in iter(self):291 yield cookie.name, cookie.value292 268- 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.297 298 .. seealso:: keys() and values().299 """300 return list(self.iteritems())301 277- 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 domains309 285- 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 paths317 293- 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.321 322 :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 jar330 306- 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.337 338 :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 dictionary347 348+ def __iter__(self) -> Iterator[Cookie]: # type: ignore[override]349+ """RequestCookieJar's __iter__ comes from CookieJar not MutableMapping."""350+ return super().__iter__()351+321- def __contains__(self, name):352+ def __contains__(self, name: object) -> bool:353 try:354 return super().__contains__(name)355 except CookieConflictError:356 return True357 327- 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.362 363 .. warning:: operation is O(n), not O(1).364 """365 return self._find_no_duplicates(name)366 336- 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)375 343- 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)381 349- 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)390 358- 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)400 366- 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.405 406 If there are conflicting cookies, _find arbitrarily chooses one.407 See _find_no_duplicates if you want an exception thrown if there are11 unmodified lines419 return cookie.value420 421 raise KeyError(f"name={name!r}, domain={domain!r}, path={path!r}")422 386- 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.428 429 :param name: a string containing name of cookie16 unmodified lines446 )447 # we will eventually return this as long as no cookie conflict448 toReturn = cookie.value449 411- if toReturn:450+ if toReturn is not None:451 return toReturn452 raise KeyError(f"name={name!r}, domain={domain!r}, path={path!r}")453 415- 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 state460 422- 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()466 428- 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_cj473 435- def get_policy(self):474+ def get_policy(self) -> CookiePolicy:475 """Return the CookiePolicy instance used."""476 return self._policy477 478 440-def _copy_cookie_jar(jar):479+def _copy_cookie_jar(jar: CookieJar | None) -> CookieJar | None: # type: ignore[reportUnusedFunction] # cross-module usage in models.py480 if jar is None:481 return None482 444- 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_jar492 493 455-def create_cookie(name, value, **kwargs):494+def create_cookie(name: str, value: str, **kwargs: Any) -> Cookie:495 """Make a cookie from underspecified parameters.496 497 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 lines527 528 return cookielib.Cookie(**result)529 530 492-def morsel_to_cookie(morsel):531+def morsel_to_cookie(morsel: Morsel[Any]) -> Cookie:532 """Convert a Morsel object into a Cookie containing the one k/v pair."""533 495- 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 lines556 version=morsel["version"] or 0,557 )558 559 521-def cookiejar_from_dict(cookie_dict, cookiejar=None, overwrite=True):560+_CookieJarT = TypeVar("_CookieJarT", bound=CookieJar)561+562+563+@overload564+def cookiejar_from_dict(565+ cookie_dict: dict[str, str] | None,566+ cookiejar: None = None,567+ overwrite: bool = True,568+) -> RequestsCookieJar: ...569+570+571+@overload572+def cookiejar_from_dict(573+ cookie_dict: dict[str, str] | None,574+ cookiejar: _CookieJarT,575+ overwrite: bool = True,576+) -> _CookieJarT: ...577+578+579+def 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.585 586 :param cookie_dict: Dict of key/values to insert into CookieJar.587 :param cookiejar: (optional) A cookiejar to add the cookies to.12 unmodified lines600 601 return cookiejar602 603 542-def merge_cookies(cookiejar, cookies):604+def merge_cookies(605+ cookiejar: CookieJar, cookies: dict[str, str] | CookieJar | None606+) -> CookieJar:607 """Add cookies to cookiejar and returns a merged CookieJar.608 609 :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")615 616 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)624 625 return cookiejarmodified:src/requests/exceptions.py+15 added-5 removed
3 unmodified lines4 5 This module contains the set of Requests' exceptions.6 """7 8+from __future__ import annotations9+10+from typing import TYPE_CHECKING, Any11+12 from urllib3.exceptions import HTTPError as BaseHTTPError13 14 from .compat import JSONDecodeError as CompatJSONDecodeError15 16+if TYPE_CHECKING:17+ from .models import PreparedRequest, Request, Response18 19+20 class RequestException(IOError):21 """There was an ambiguous exception that occurred while handling your22 request.23 """24 18- def __init__(self, *args, **kwargs):25+ response: Response | None26+ request: Request | PreparedRequest | None27+28+ 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)36 37 38 class InvalidJSONError(RequestException):2 unmodified lines41 42 class JSONDecodeError(InvalidJSONError, CompatJSONDecodeError):43 """Couldn't decode the text into json"""44 35- 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 args1 unmodified line51 """52 CompatJSONDecodeError.__init__(self, *args)53 InvalidJSONError.__init__(self, *self.args, **kwargs)54 45- 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 just103 unmodified linesmodified:src/requests/help.py+14 added-11 removed
1 """Module containing bug report helper(s)."""2 3+# pyright: reportUnknownMemberType=false4+5 import json6 import platform7 import ssl8 import sys9+from typing import Any10 11 import idna12 import urllib313 4 unmodified lines18 except ImportError:19 charset_normalizer = None20 21 try:19- import chardet22+ import chardet # type: ignore[import-not-found]23 except ImportError:24 chardet = None25 26 try:2 unmodified lines29 pyopenssl = None30 OpenSSL = None31 cryptography = None32 else:30- import cryptography31- import OpenSSL33+ import cryptography # type: ignore[import-not-found]34+ import OpenSSL # type: ignore[import-not-found]35 36 37 def _implementation():38 """Return a dict with the Python implementation and version.10 unmodified lines49 50 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 lines65 66 return {"name": implementation, "version": implementation_version}67 68 66-def info():69+def info() -> dict[str, Any]:70 """Generate information for a bug report."""71 try:72 platform_info = {73 "system": platform.system(),5 unmodified lines79 "release": "Unknown",80 }81 82 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__}90 88- pyopenssl_info = {91+ pyopenssl_info: dict[str, str | None] = {92 "version": None,93 "openssl_version": "",94 }95 if OpenSSL:8 unmodified lines104 "version": getattr(idna, "__version__", ""),105 }106 107 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]109 110 return {111 "platform": platform_info,112 "implementation": implementation_info,22 unmodified linesmodified:src/requests/hooks.py+23 added-9 removed
8 unmodified lines9 ``response``:10 The response generated from a Request.11 """12 13-HOOKS = ["response"]13+from __future__ import annotations14 15+from collections.abc import Callable, Iterable16+from typing import TYPE_CHECKING, Any17 16-def default_hooks():18+if TYPE_CHECKING:19+ from . import _types as _t20+ from .models import Response21+22+HOOKS: list[str] = ["response"]23+24+25+def default_hooks() -> dict[str, list[_t.HookType]]:26 return {event: [] for event in HOOKS}27 28 29 # TODO: response is the only one30 31 23-def dispatch_hook(key, hooks, hook_data, **kwargs):32+def 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_datamodified:src/requests/models.py+257 added-123 removed
3 unmodified lines4 5 This module contains the primary objects that power Requests.6 """7 8+from __future__ import annotations9+10 import datetime11 12 # 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.13-import encodings.idna # noqa: F40115+import encodings.idna # noqa: F401 # type: ignore[reportUnusedImport]16+from collections.abc import Callable, Generator, Iterable, Iterator, Mapping17 from io import UnsupportedOperation18+from typing import (19+ TYPE_CHECKING,20+ Any,21+ Final,22+ Literal,23+ cast,24+ overload,25+)26 27 from urllib3.exceptions import (28 DecodeError,29 LocationParseError,5 unmodified lines35 from urllib3.filepost import encode_multipart_formdata36 from urllib3.util import parse_url37 38 from ._internal_utils import to_native_string, unicode_is_ascii39+from ._types import SupportsRead as _SupportsRead40 from .auth import HTTPBasicAuth41 from .compat import (30- Callable,42 JSONDecodeError,32- Mapping,43 basestring,44 builtin_str,45 chardet,46 cookielib,1 unmodified line48 urlsplit,49 urlunparse,50 )51 from .compat import json as complexjson42-from .cookies import _copy_cookie_jar, cookiejar_from_dict, get_cookie_header52+from .cookies import (53+ _copy_cookie_jar, # type: ignore[reportPrivateUsage]54+ cookiejar_from_dict,55+ get_cookie_header,56+)57 from .exceptions import (58 ChunkedEncodingError,59 ConnectionError,60 ContentDecodingError,20 unmodified lines81 super_len,82 to_key_val_list,83 )84 85+if TYPE_CHECKING:86+ from http.cookiejar import CookieJar87+88+ from typing_extensions import Self89+90+ from . import _types as _t91+ from .adapters import HTTPAdapter92+ from .cookies import RequestsCookieJar93+94 #: The set of HTTP status codes that indicate an automatically95 #: processable redirect.73-REDIRECT_STATI = (96+REDIRECT_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 )103 81-DEFAULT_REDIRECT_LIMIT = 3082-CONTENT_CHUNK_SIZE = 10 * 102483-ITER_CHUNK_SIZE = 512104+DEFAULT_REDIRECT_LIMIT: int = 30105+CONTENT_CHUNK_SIZE: int = 10 * 1024106+ITER_CHUNK_SIZE: int = 512107 108 109 class RequestEncodingMixin:110+ url: str | None111+112 @property88- def path_url(self):113+ def path_url(self) -> str:114 """Build the path URL to use."""115 91- url = []116+ url: list[str] = []117 93- p = urlsplit(self.url)118+ p = urlsplit(cast(str, self.url))119 120 path = p.path121 if not path:122 path = "/"6 unmodified lines129 url.append(query)130 131 return "".join(url)132 133+ @overload134 @staticmethod109- def _encode_params(data):135+ def _encode_params(data: str) -> str: ...136+137+ @overload138+ @staticmethod139+ def _encode_params(data: bytes) -> bytes: ...140+141+ @overload142+ @staticmethod143+ def _encode_params(144+ data: _t.SupportsRead[str | bytes],145+ ) -> _t.SupportsRead[str | bytes]: ...146+147+ @overload148+ @staticmethod149+ def _encode_params(data: _t.KVDataType) -> str: ...150+151+ @staticmethod152+ def _encode_params(153+ data: _t.EncodableDataType,154+ ) -> str | bytes | _t.SupportsRead[str | bytes]:155 """Encode parameters in a piece of data.156 157 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 arbitrary1 unmodified line160 """161 162 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 lines177 )178 )179 return urlencode(result, doseq=True)180 else:136- return data181+ return data # type: ignore[return-value] # unreachable for valid _t.DataType182 183 @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.188 189 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 arbitrary5 unmodified lines196 raise ValueError("Files must be provided.")197 elif isinstance(data, basestring):198 raise ValueError("Data must not be a string.")199 153- 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 {})203 204 for field, val in fields:30 unmodified lines235 fp = v236 237 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 lines252 return body, content_type253 254 255 class RequestHooksMixin:209- def register_hook(self, event, hook):256+ hooks: dict[str, list[_t.HookType]]257+258+ def register_hook(259+ self, event: str, hook: Iterable[_t.HookType] | _t.HookType260+ ) -> None:261 """Properly register a hook."""262 263 if event not in self.hooks:264 raise ValueError(f'Unsupported event specified, with event name "{event}"')265 266 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 filter270 220- 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 lines307 >>> req.prepare()308 <PreparedRequest [GET]>309 """310 311+ 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] | None320+321 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 headers13 unmodified lines351 self.params = params352 self.auth = auth353 self.cookies = cookies354 294- def __repr__(self):355+ def __repr__(self) -> str:356 return f"<Request [{self.method}]>"357 297- 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 lines393 >>> s.send(r)394 <Response [200]>395 """396 397+ 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 | None404+336- 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 lines420 self._body_position = None421 422 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."""436 437+ 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 lines447 448 # This MUST go after prepare_auth. Authenticators could add a hook449 self.prepare_hooks(hooks)450 381- def __repr__(self):451+ def __repr__(self) -> str:452 return f"<PreparedRequest [{self.method}]>"453 384- 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 p464 395- 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())470 471 @staticmethod402- def _get_idna_encoded_host(host):472+ def _get_idna_encoded_host(host: str) -> str:473 import idna474 475 try:476 host = idna.encode(host, uts46=True).decode("utf-8")477 except idna.IDNAError:478 raise UnicodeError479 return host480 411- 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 lines545 546 if isinstance(params, (str, bytes)):547 params = to_native_string(params)548 549+ if params is not None:475- enc_params = self._encode_params(params)550+ enc_params = self._encode_params(params)551+ else:552+ enc_params = ""553+554 if enc_params:555 if query:556 query = f"{query}&{enc_params}"557 else:558 query = enc_params559 482- url = requote_uri(urlunparse([scheme, netloc, path, None, query, fragment]))560+ url = requote_uri(urlunparse((scheme, netloc, path, "", query, fragment)))561 self.url = url562 485- def prepare_headers(self, headers):563+ def prepare_headers(self, headers: Mapping[str, str | bytes] | None) -> None:564 """Prepares the given HTTP headers."""565 566 self.headers = CaseInsensitiveDict()567 if headers:2 unmodified lines570 check_header_validity(header)571 name, value = header572 self.headers[to_native_string(name)] = value573 496- 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."""578 579 # Check if file, fo, generator, iterator.580 # If not, run through normal process.14 unmodified lines595 596 if not isinstance(body, bytes):597 body = body.encode("utf-8")598 519- is_stream = all(520- [521- hasattr(data, "__iter__"),522- not isinstance(data, (basestring, list, tuple, Mapping)),523- ]524- )525-526- 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 = None4 unmodified lines610 # 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 lines626 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)632+633 # 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 lines646 # 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_type649 572- self.body = body650+ self.body = body # type: ignore[assignment] # body transforms from DataType to BodyType651 574- 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 lines664 # 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"667 590- 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."""674 675 # 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 None679 680 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)687 688 # Allow auth to make its changes.604- r = auth(self)689+ r = auth_handler(self)690 691 # Update self to reflect the auth changes.692 self.__dict__.update(r.__dict__)693 694 # Recompute Content-Length695 self.prepare_content_length(self.body)696 612- 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.701 702 This function eventually generates a ``Cookie`` header from the703 given cookies using cookielib. Due to cookielib's design, the header7 unmodified lines711 self._cookies = cookies712 else:713 self._cookies = cookiejar_from_dict(cookies)714 715+ 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_header719 632- 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])728 729 1 unmodified line731 """The :class:`Response <Response>` object, which contains a732 server's response to an HTTP request.733 """734 647- __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: HTTPAdapter749+750+ __attrs__: list[str] = [751 "_content",752 "status_code",753 "headers",754 "url",4 unmodified lines759 "elapsed",760 "request",761 ]762 660- def __init__(self):763+ def __init__(self) -> None:764 self._content = False765 self._content_consumed = False766 self._next = None767 768 #: Integer Code of responded HTTP Status, e.g. 404 or 200.666- self.status_code = None769+ self.status_code = None # type: ignore[assignment]770 771 #: Case-insensitive Dictionary of Response Headers.772 #: For example, ``headers['content-encoding']`` will return the773 #: value of a ``'Content-Encoding'`` response header.4 unmodified lines778 #: This requirement does not apply for use internally to Requests.779 self.raw = None780 781 #: Final URL location of Response.679- self.url = None782+ self.url = None # type: ignore[assignment]783 784 #: Encoding to decode with when accessing r.text.785 self.encoding = None786 17 unmodified lines804 self.elapsed = datetime.timedelta(0)805 806 #: The :class:`PreparedRequest <PreparedRequest>` object to which this807 #: is a response.705- self.request = None808+ self.request = None # type: ignore[assignment]809 707- def __enter__(self):810+ def __enter__(self) -> Self:811 return self812 710- def __exit__(self, *args):813+ def __exit__(self, *args: Any) -> None:814 self.close()815 713- 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.content821 822 return {attr: getattr(self, attr, None) for attr in self.__attrs__}823 721- 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)827 828 # pickled objects do not have .raw829 setattr(self, "_content_consumed", True)830 setattr(self, "raw", None)831 729- def __repr__(self):832+ def __repr__(self) -> str:833 return f"<Response [{self.status_code}]>"834 732- def __bool__(self):835+ def __bool__(self) -> bool:836 """Returns True if :attr:`status_code` is less than 400.837 838 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. If1 unmodified line841 is **not** a check to see if the response code is ``200 OK``.842 """843 return self.ok844 742- def __nonzero__(self):845+ def __nonzero__(self) -> bool:846 """Returns True if :attr:`status_code` is less than 400.847 848 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. If1 unmodified line851 is **not** a check to see if the response code is ``200 OK``.852 """853 return self.ok854 752- 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)858 859 @property757- def ok(self):860+ def ok(self) -> bool:861 """Returns True if :attr:`status_code` is less than 400, False if not.862 863 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. If6 unmodified lines871 return False872 return True873 874 @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_STATI880 881 @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 )888 889 @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._next893 894 @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"903 801- 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 item10 unmodified lines929 bytes will be returned. This can be bypassed by manually setting930 `encoding` on the response.931 """932 820- 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 lines954 self._content_consumed = True955 956 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)962 963+ 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()969 854- chunks = reused_chunks if self._content_consumed else stream_chunks855-970 if decode_unicode:971 chunks = stream_decode_response_unicode(chunks, self)972 973 return chunks974 975+ @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 lines1002 1003 .. note:: This method is not reentrant safe.1004 """1005 874- pending = None1006+ pending: str | bytes | None = None1007 1008 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]1014 1015 if delimiter:883- lines = chunk.split(delimiter)1016+ lines = chunk.split(delimiter) # type: ignore[arg-type]1017 else:1018 lines = chunk.splitlines()1019 1020 if lines and lines[-1] and chunk and lines[-1][-1] == chunk[-1]:6 unmodified lines1027 if pending is not None:1028 yield pending1029 1030 @property898- def content(self):1031+ def content(self) -> bytes:1032 """Content of the response, in bytes."""1033 1034 if self._content is False:1035 # Read the contents.7 unmodified lines1043 1044 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]1048 1049 @property917- def text(self):1050+ def text(self) -> str:1051 """Content of the response, in unicode.1052 1053 If Response.encoding is None, encoding will be guessed using1054 ``charset_normalizer`` or ``chardet``.16 unmodified lines1071 encoding = self.apparent_encoding1072 1073 # 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 lines1083 content = str(self.content, errors="replace")1084 1085 return content1086 954- def json(self, **kwargs):1087+ def json(self, **kwargs: Any) -> Any:1088 r"""Decodes the JSON response body (if any) as a Python object.1089 1090 This may return a dictionary, list, etc. depending on what is in the response.1091 27 unmodified lines1119 # This aliases json.JSONDecodeError and simplejson.JSONDecodeError1120 raise RequestsJSONDecodeError(e.msg, e.doc, e.pos)1121 1122 @property990- def links(self):1123+ def links(self) -> dict[str, dict[str, str]]:1124 """Returns the parsed header links of the response, if any."""1125 1126 header = self.headers.get("link")1127 995- resolved_links = {}1128+ resolved_links: dict[str, dict[str, str]] = {}1129 1130 if header:1131 links = parse_header_links(header)1132 1133 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] = link1137 1138 return resolved_links1139 1006- def raise_for_status(self):1140+ def raise_for_status(self) -> None:1141 """Raises :class:`HTTPError`, if one occurred."""1142 1143 http_error_msg = ""1144 if isinstance(self.reason, bytes):20 unmodified lines1165 1166 if http_error_msg:1167 raise HTTPError(http_error_msg, response=self)1168 1035- 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.1172 1173 *Note: Should not normally need to be called explicitly.*7 unmodified linesadded:src/requests/py.typed
modified:src/requests/sessions.py+155 added-75 removed
4 unmodified lines5 This module provides a Session object to manage and persist settings across6 requests (cookies, auth, proxies).7 """8 9+from __future__ import annotations10+11 import os12 import sys13 import time14 from collections import OrderedDict15+from collections.abc import Generator, Mapping, MutableMapping16 from datetime import timedelta17+from typing import TYPE_CHECKING, Any, cast18 19 from ._internal_utils import to_native_string20+from ._types import is_prepared as _is_prepared21 from .adapters import HTTPAdapter17-from .auth import _basic_auth_str18-from .compat import Mapping, cookielib, urljoin, urlparse22+from .auth import _basic_auth_str # type: ignore[reportPrivateUsage]23+from .compat import cookielib, urljoin, urlparse24 from .cookies import (25 RequestsCookieJar,26 cookiejar_from_dict,27 extract_cookies_to_jar,9 unmodified lines37 38 # formerly defined here, reexposed here for backward compatibility39 from .models import ( # noqa: F40140 DEFAULT_REDIRECT_LIMIT,36- REDIRECT_STATI,41+ REDIRECT_STATI, # type: ignore[reportUnusedImport]42 PreparedRequest,43 Request,44+ Response,45 )46 from .status_codes import codes47 from .structures import CaseInsensitiveDict48 from .utils import ( # noqa: F4014 unmodified lines53 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 )60 61+if TYPE_CHECKING:62+ from http.cookiejar import CookieJar63+64+ from typing_extensions import Self, Unpack65+66+ from . import _types as _t67+ from .adapters import BaseAdapter68+69 # Preferred clock, based on which one is more accurate on a given system.70 if sys.platform == "win32":71 preferred_clock = time.perf_counter72 else:73 preferred_clock = time.time74 75 62-def merge_setting(request_setting, session_setting, dict_class=OrderedDict):76+def 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 lines92 isinstance(session_setting, Mapping) and isinstance(request_setting, Mapping)93 ):94 return request_setting95 80- 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]98 99 # 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 lines104 105 return merged_setting106 107 92-def merge_hooks(request_hooks, session_hooks, dict_class=OrderedDict):108+def 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.114 115 This is necessary because when request_hooks == {'response': []}, the116 merge breaks Session hooks entirely.7 unmodified lines124 return merge_setting(request_hooks, session_hooks, dict_class)125 126 127 class SessionRedirectMixin:128+ max_redirects: int129+ trust_env: bool130+ cookies: RequestsCookieJar131+132+ def send(self, request: PreparedRequest, **kwargs: Any) -> Response: ...133+108- 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 lines150 location = location.encode("latin1")151 return to_native_string(location, "utf8")152 return None153 128- 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 lines184 return changed_port or changed_scheme185 186 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."""199 174- hist = [] # keep track of history200+ hist: list[Response] = [] # keep track of history201 202 url = self.get_redirect_target(resp)203 previous_fragment = urlparse(req.url).fragment204 while url:57 unmodified lines262 263 # 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)270 271 # Rebuild auth and proxy information.272 proxies = self.rebuild_proxies(prepared_request, proxies)273 self.rebuild_auth(prepared_request, resp)274 275 # 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 )281 282 # Attempt to rewind consumed file-like object.3 unmodified lines286 # Override the original request.287 req = prepared_request288 289 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 lines305 # extract redirect url, if any, for the next loop306 url = self.get_redirect_target(resp)307 yield resp308 282- 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)319+320 headers = prepared_request.headers321+ original_url = original_request.url322 url = prepared_request.url323 290- 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 line330 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)333 302- 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 previous3 unmodified lines346 necessary.347 348 :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 lines366 headers["Proxy-Authorization"] = _basic_auth_str(username, password)367 368 return new_proxies369 333- 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.method33 unmodified lines410 ... s.get('https://httpbin.org/get')411 <Response [200]>412 """413 414+ 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]426+375- __attrs__ = [427+ __attrs__: list[str] = [428 "headers",429 "cookies",430 "auth",431 "proxies",6 unmodified lines438 "trust_env",439 "max_redirects",440 ]441 390- 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 lines501 self.adapters = OrderedDict()502 self.mount("https://", HTTPAdapter())503 self.mount("http://", HTTPAdapter())504 453- def __enter__(self):505+ def __enter__(self) -> Self:506 return self507 456- def __exit__(self, *args):508+ def __exit__(self, *args: Any) -> None:509 self.close()510 459- 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 line517 :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)523+524 cookies = request.cookies or {}525 526 # Bootstrap CookieJar.527 if not isinstance(cookies, cookielib.CookieJar):6 unmodified lines534 535 # 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)539 540 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 lines555 return p556 557 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.578 579 :param method: method for the new :class:`Request` object.35 unmodified lines615 :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")621+622 # Create the Request.623 req = Request(624 method=method.upper(),625 url=url,7 unmodified lines633 hooks=hooks,634 )635 prep = self.prepare_request(req)636 637+ assert _is_prepared(prep)638+639 proxies = proxies or {}640 641 settings = self.merge_environment_settings(642 prep.url, proxies, stream, verify, cert8 unmodified lines651 resp = self.send(prep, **send_kwargs)652 653 return resp654 595- 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.657 658 :param url: URL for the new :class:`Request` object.659 :param \*\*kwargs: Optional arguments that ``request`` takes.2 unmodified lines662 663 kwargs.setdefault("allow_redirects", True)664 return self.request("GET", url, **kwargs)665 606- 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.668 669 :param url: URL for the new :class:`Request` object.670 :param \*\*kwargs: Optional arguments that ``request`` takes.2 unmodified lines673 674 kwargs.setdefault("allow_redirects", True)675 return self.request("OPTIONS", url, **kwargs)676 617- 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.679 680 :param url: URL for the new :class:`Request` object.681 :param \*\*kwargs: Optional arguments that ``request`` takes.2 unmodified lines684 685 kwargs.setdefault("allow_redirects", False)686 return self.request("HEAD", url, **kwargs)687 628- 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.696 697 :param url: URL for the new :class:`Request` object.698 :param data: (optional) Dictionary, list of tuples, bytes, or file-like4 unmodified lines703 """704 705 return self.request("POST", url, data=data, json=json, **kwargs)706 641- 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.711 712 :param url: URL for the new :class:`Request` object.713 :param data: (optional) Dictionary, list of tuples, bytes, or file-like3 unmodified lines717 """718 719 return self.request("PUT", url, data=data, **kwargs)720 653- 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.725 726 :param url: URL for the new :class:`Request` object.727 :param data: (optional) Dictionary, list of tuples, bytes, or file-like3 unmodified lines731 """732 733 return self.request("PATCH", url, data=data, **kwargs)734 665- 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.737 738 :param url: URL for the new :class:`Request` object.739 :param \*\*kwargs: Optional arguments that ``request`` takes.1 unmodified line741 """742 743 return self.request("DELETE", url, **kwargs)744 675- def send(self, request, **kwargs):745+ def send(self, request: PreparedRequest, **kwargs: Any) -> Response:746 """Send a given PreparedRequest.747 748 :rtype: requests.Response749 """9 unmodified lines759 # Guard against that specific failure case.760 if isinstance(request, Request):761 raise ValueError("You can only send PreparedRequests.")762 763+ assert _is_prepared(request)764+765 # 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.hooks40 unmodified lines809 810 # 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 pass2 unmodified lines820 r.content821 822 return r823 752- 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.834 835 :rtype: dict2 unmodified lines838 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)845 846 # Look for requests environment configuration847 # and be compatible with cURL.848 if verify is True or verify is None:10 unmodified lines859 cert = merge_setting(cert, self.cert)860 861 return {"proxies": proxies, "stream": stream, "verify": verify, "cert": cert}862 783- def get_adapter(self, url):863+ def get_adapter(self, url: str) -> BaseAdapter:864 """865 Returns the appropriate connection adapter for the given URL.866 867 :rtype: requests.adapters.BaseAdapter4 unmodified lines872 873 # Nothing matches :-/874 raise InvalidSchema(f"No connection adapters were found for {url!r}")875 796- 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()880 801- def mount(self, prefix, adapter):881+ def mount(self, prefix: str, adapter: BaseAdapter) -> None:882 """Registers a connection adapter to a prefix.883 884 Adapters are sorted in descending order by prefix length.885 """2 unmodified lines888 889 for key in keys_to_move:890 self.adapters[key] = self.adapters.pop(key)891 812- def __getstate__(self):892+ def __getstate__(self) -> dict[str, Any]:893 state = {attr: getattr(self, attr, None) for attr in self.__attrs__}894 return state895 816- 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)899 900 821-def session():901+def session() -> Session:902 """903 Returns a :class:`Session` for context-management.904 905 .. deprecated:: 1.0.08 unmodified linesmodified:src/requests/status_codes.py+2 added-2 removed
101 unmodified lines102 510: ("not_extended",),103 511: ("network_authentication_required", "network_auth", "network_authentication"),104 }105 106-codes = LookupDict(name="status_codes")106+codes: LookupDict[int] = LookupDict(name="status_codes")107 108 109 def _init():110 for code, titles in _codes.items():1 unmodified line112 setattr(codes, title, code)113 if not title.startswith(("\\", "/")):114 setattr(codes, title.upper(), code)115 116- 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)119 120 global __doc__8 unmodified linesmodified:src/requests/structures.py+51 added-20 removed
3 unmodified lines4 5 Data structures that power Requests.6 """7 8+from __future__ import annotations9+10 from collections import OrderedDict11+from collections.abc import Iterable, Iterator, Mapping12+from typing import Any, Generic, TypeVar, overload13 10-from .compat import Mapping, MutableMapping14+from .compat import MutableMapping15 16+_VT = TypeVar("_VT")17+_D = TypeVar("_D")18 19+13-class CaseInsensitiveDict(MutableMapping):20+class CaseInsensitiveDict(MutableMapping[str, _VT], Generic[_VT]):21 """A case-insensitive ``dict``-like object.22 23 Implements all methods and operations of24 ``MutableMapping`` as well as dict's ``copy``. Also18 unmodified lines43 operations are given keys that have equal ``.lower()``s, the44 behavior is undefined.45 """46 40- def __init__(self, data=None, **kwargs):47+ _store: OrderedDict[str, tuple[str, _VT]]48+49+ 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)58 46- 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)63 51- def __getitem__(self, key):64+ def __getitem__(self, key: str) -> _VT:65 return self._store[key.lower()][1]66 54- def __delitem__(self, key):67+ def __delitem__(self, key: str) -> None:68 del self._store[key.lower()]69 57- 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())72 60- def __len__(self):73+ def __len__(self) -> int:74 return len(self._store)75 63- 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())79 67- 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())87 88 # Copy is required76- def copy(self):89+ def copy(self) -> CaseInsensitiveDict[_VT]:90 return CaseInsensitiveDict(self._store.values())91 79- def __repr__(self):92+ def __repr__(self) -> str:93 return str(dict(self.items()))94 95 83-class LookupDict(dict):96+class LookupDict(dict[str, _VT]):97 """Dictionary lookup object."""98 99+ name: Any100+86- def __init__(self, name=None):101+ def __init__(self, name: Any = None) -> None:102 self.name = name103 super().__init__()104 90- def __repr__(self):105+ def __repr__(self) -> str:106 return f"<lookup '{self.name}'>"107 93- 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+ )117+118+ def __getitem__(self, key: str) -> _VT | None: # type: ignore[override]119 # We allow fall-through here, so values default to None120 121 return self.__dict__.get(key, None)122 98- def get(self, key, default=None):123+ @overload124+ def get(self, key: str, default: None = None) -> _VT | None: ...125+126+ @overload127+ def get(self, key: str, default: _D | _VT) -> _D | _VT: ...128+129+ 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 lines5 This module provides utility functions that are used within Requests6 that are also useful for external consumption.7 """8 9+from __future__ import annotations10+11 import codecs12 import contextlib13 import io14 import os4 unmodified lines19 import tempfile20 import warnings21 import zipfile22 from collections import OrderedDict23+from collections.abc import Generator, Iterable24+from typing import (25+ TYPE_CHECKING,26+ Any,27+ Final,28+ TypeVar,29+ cast,30+ overload,31+)32 33 from urllib3.util import make_headers, parse_url34 35 from . import certs36 from .__version__ import __version__37 38 # to_native_string is unused here, but imported here for backwards compatibility39 from ._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 )45+from ._types import SupportsItems as _SupportsItems46 from .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 lines67 UnrewindableBodyError,68 )69 from .structures import CaseInsensitiveDict70 60-NETRC_FILES = (".netrc", "_netrc")71+if TYPE_CHECKING:72+ from http.cookiejar import CookieJar73+ from io import BufferedWriter74 75+ from . import _types as _t76+ from .models import PreparedRequest, Request, Response77+78+NETRC_FILES: Final = (".netrc", "_netrc")79+80+81 # Certificate is extracted by certifi when needed.63-DEFAULT_CA_BUNDLE_PATH = certs.where()82+DEFAULT_CA_BUNDLE_PATH: str = certs.where()83 65-DEFAULT_PORTS = {"http": 80, "https": 443}84 85+DEFAULT_PORTS: Final = {"http": 80, "https": 443}86+87+_KT = TypeVar("_KT")88+_VT = TypeVar("_VT")89+90 # Ensure that ', ' is used to preserve previous delimiter behavior.68-DEFAULT_ACCEPT_ENCODING = ", ".join(91+DEFAULT_ACCEPT_ENCODING: Final = ", ".join(92 re.split(r",\s*", make_headers(accept_encoding=True)["accept-encoding"])93 )94 95 96 if sys.platform == "win32":97 # provide a proxy_bypass version on Windows without DNS lookups98 76- def proxy_bypass_registry(host):99+ def proxy_bypass_registry(host: str) -> bool:100 try:101 import winreg102 except ImportError:103 return False29 unmodified lines133 if re.match(test, host, re.I):134 return True135 return False136 114- def proxy_bypass(host): # noqa137+ def proxy_bypass(host: str) -> bool: # noqa138 """Return True, if the host should be bypassed.139 140 Checks proxy settings gathered from the environment, if specified,141 or the registry.3 unmodified lines145 else:146 return proxy_bypass_registry(host)147 148 126-def dict_to_sequence(d):149+def dict_to_sequence(150+ d: _t.SupportsItems | Iterable[tuple[Any, Any]],151+) -> Iterable[tuple[Any, Any]]:152 """Returns an internal sequence dictionary update."""153 129- if hasattr(d, "items"):130- d = d.items()154+ if isinstance(d, _SupportsItems):155+ return d.items()156 157 return d158 159 135-def super_len(o):160+def super_len(o: Any) -> int:161 total_length = None162 current_position = 0163 164 if not is_urllib3_1 and isinstance(o, str):62 unmodified lines227 228 return max(0, total_length - current_position)229 230 206-def get_netrc_auth(url, raise_errors=False):231+def 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."""235 236+ if isinstance(url, bytes):237+ url = url.decode("utf-8")238+239 netrc_file = os.environ.get("NETRC")240 if netrc_file is not None:241 netrc_locations = (netrc_file,)242 else:16 unmodified lines259 260 ri = urlparse(url)261 host = ri.hostname262 263+ if host is None:264+ return265+266 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 lines279 except (ImportError, AttributeError):280 pass281 282 250-def guess_filename(obj):283+def 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 only288 289 257-def extract_zipped_paths(path):290+def 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 lines325 return extracted_path326 327 328 @contextlib.contextmanager296-def atomic_open(filename):329+def 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 lines337 os.remove(tmp_name)338 raise339 340 308-def from_key_val_list(value):341+def 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 lines366 367 return OrderedDict(value)368 369 370+@overload371+def to_key_val_list(value: None) -> None: ...372+@overload335-def to_key_val_list(value):373+def to_key_val_list(374+ value: Mapping[_KT, _VT] | Iterable[tuple[_KT, _VT]],375+) -> list[tuple[_KT, _VT]]: ...376+def 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.,381 382 ::14 unmodified lines397 398 if isinstance(value, (str, bytes, bool, int)):399 raise ValueError("cannot encode objects that are not 2-tuples")400 358- if isinstance(value, Mapping):359- value = value.items()401+ if isinstance(value, _SupportsItems):402+ return list(value.items())403 404 return list(value)405 406 407 # From mitsuhiko/werkzeug (used with permission).365-def parse_list_header(value):408+def parse_list_header(value: str) -> list[str]:409 """Parse lists as described by RFC 2068 Section 2.410 411 In particular, parse comma-separated lists where the elements of412 the list may include quoted-strings. A quoted-string could14 unmodified lines427 :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 result437 438 439 # From mitsuhiko/werkzeug (used with permission).397-def parse_dict_header(value):440+def 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:443 444 >>> d = parse_dict_header('foo="is a fish", bar="as well"')13 unmodified lines458 :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 continue4 unmodified lines471 return result472 473 474 # From mitsuhiko/werkzeug (used with permission).432-def unquote_header_value(value, is_filename=False):475+def 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 lines496 return value.replace("\\\\", "\\").replace('\\"', '"')497 return value498 499 457-def dict_from_cookiejar(cj):500+def dict_from_cookiejar(cj: CookieJar) -> dict[str, str | None]:501 """Returns a key/value dictionary from a CookieJar.502 503 :param cj: CookieJar object to extract cookies from.504 :rtype: dict2 unmodified lines507 cookie_dict = {cookie.name: cookie.value for cookie in cj}508 return cookie_dict509 510 468-def add_dict_to_cookiejar(cj, cookie_dict):511+def add_dict_to_cookiejar(cj: CookieJar, cookie_dict: dict[str, str]) -> CookieJar:512 """Returns a CookieJar from a key/value dictionary.513 514 :param cj: CookieJar to insert cookies into.515 :param cookie_dict: Dict of key/values to insert into CookieJar.2 unmodified lines518 519 return cookiejar_from_dict(cookie_dict, cj)520 521 479-def get_encodings_from_content(content):522+def get_encodings_from_content(content: str) -> list[str]:523 """Returns encodings from given content string.524 525 :param content: bytestring to extract encodings from.526 """16 unmodified lines543 + xml_re.findall(content)544 )545 546 504-def _parse_content_type_header(header):547+def _parse_content_type_header(header: str) -> tuple[str, dict[str, Any]]:548 """Returns content type and parameters from given header.549 550 :param header: string551 :return: tuple containing content type and dictionary of1 unmodified line553 """554 555 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 = "\"' "559 560 for param in params:561 param = param.strip()3 unmodified lines565 params_dict[key.lower()] = value566 return content_type, params_dict567 568 526-def get_encoding_from_headers(headers):569+def get_encoding_from_headers(headers: CaseInsensitiveDict[str]) -> str | None:570 """Returns encodings from given HTTP Header Dict.571 572 :param headers: dictionary to extract encoding from.573 :rtype: str16 unmodified lines590 # Assume UTF-8 based on RFC 4627: https://www.ietf.org/rfc/rfc4627.txt since the charset was unset591 return "utf-8"592 593 551-def stream_decode_response_unicode(iterator, r):594+def stream_decode_response_unicode(595+ iterator: Iterable[bytes], r: Response596+) -> Generator[str | bytes, None, None]:597 """Stream decodes an iterator."""598 599 if r.encoding is None:600 yield from iterator8 unmodified lines609 if rv:610 yield rv611 612 568-def iter_slices(string, slice_length):613+@overload614+def iter_slices(615+ string: bytes, slice_length: int | None616+) -> Generator[bytes, None, None]: ...617+@overload618+def iter_slices(619+ string: str, slice_length: int | None620+) -> Generator[str, None, None]: ...621+def 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 line629 yield string[pos : pos + slice_length]630 pos += slice_length631 632 578-def get_unicode_from_response(r):633+def get_unicode_from_response(r: Response) -> str | bytes | None:634 """Returns the requested content back in unicode.635 636 :param r: Response object to get unicode content from.637 11 unmodified lines649 " warning should only appear once.)"650 ),651 DeprecationWarning,652 )653+ if r.content is None: # type: ignore[reportUnnecessaryComparison]654+ return None655 599- tried_encodings = []656+ tried_encodings: list[str] = []657 658 # Try charset from content-type659 encoding = get_encoding_from_headers(r.headers)660 4 unmodified lines665 tried_encodings.append(encoding)666 667 # 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.content672 673 674 # The unreserved URI characters (RFC 3986)618-UNRESERVED_SET = frozenset(675+UNRESERVED_SET: Final = frozenset(676 "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz" + "0123456789-._~"677 )678 679 623-def unquote_unreserved(uri):680+def 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.683 684 :rtype: str15 unmodified lines700 parts[i] = f"%{parts[i]}"701 return "".join(parts)702 703 647-def requote_uri(uri):704+def requote_uri(uri: str) -> str:705 """Re-quote the given URI.706 707 This function passes the given URI through an unquote/quote cycle to708 ensure that it is fully and consistently quoted.13 unmodified lines722 # properly quoted so they do not cause issues elsewhere.723 return quote(uri, safe=safe_without_percent)724 725 669-def address_in_network(ip, net):726+def address_in_network(ip: str, net: str) -> bool:727 """This function allows you to check if an IP belongs to a network subnet728 729 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/246 unmodified lines737 network = struct.unpack("=L", socket.inet_aton(netaddr))[0] & netmask738 return (ipaddr & netmask) == (network & netmask)739 740 684-def dotted_netmask(mask):741+def dotted_netmask(mask: int) -> str:742 """Converts mask from /xx format to xxx.xxx.xxx.xxx743 744 Example: if mask is 24 function returns 255.255.255.0745 2 unmodified lines748 bits = 0xFFFFFFFF ^ (1 << 32 - mask) - 1749 return socket.inet_ntoa(struct.pack(">I", bits))750 751 695-def is_ipv4_address(string_ip):752+def is_ipv4_address(string_ip: str) -> bool:753 """754 :rtype: bool755 """756 try:2 unmodified lines759 return False760 return True761 762 706-def is_valid_cidr(string_network):763+def is_valid_cidr(string_network: str) -> bool:764 """765 Very simple check of the cidr format in no_proxy variable.766 767 :rtype: bool16 unmodified lines784 return True785 786 787 @contextlib.contextmanager731-def set_environ(env_name, value):788+def set_environ(env_name: str, value: str | None) -> Generator[None, None, None]:789 """Set the environment variable 'env_name' to 'value'790 791 Save previous value, yield, and then restore the previous value stored in792 the environment variable 'env_name'.793 794 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 lines806 else:807 os.environ[env_name] = old_value808 809 752-def should_bypass_proxies(url, no_proxy):810+def should_bypass_proxies(url: str, no_proxy: str | None) -> bool:811 """812 Returns whether we should bypass proxies or not.813 814 :rtype: bool815 """816 817 # 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())821 822 # 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.hostname829 771- if parsed.hostname is None:830+ if hostname is None:831 # URLs don't always have hostnames, e.g. file:/// urls.832 return True833 834 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)838 780- 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}"852 794- 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 True858 859 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 = False864 865 if bypass:1 unmodified line867 868 return False869 870 813-def get_environ_proxies(url, no_proxy=None):871+def get_environ_proxies(url: str, no_proxy: str | None = None) -> dict[str, str]:872 """873 Return a dict of environment proxies.874 875 :rtype: dict3 unmodified lines879 else:880 return getproxies()881 882 825-def select_proxy(url, proxies):883+def select_proxy(url: str, proxies: dict[str, str] | None) -> str | None:884 """Select a proxy for the url, if applicable.885 886 :param url: The url being for the request887 :param proxies: A dictionary of schemes or schemes and hosts to proxy URLs17 unmodified lines905 906 return proxy907 908 851-def resolve_proxies(request, proxies, trust_env=True):909+def 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 lines921 922 :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 lines936 new_proxies.setdefault(scheme, proxy)937 return new_proxies938 939 878-def default_user_agent(name="python-requests"):940+def default_user_agent(name: str = "python-requests") -> str:941 """942 Return a string representing the default user agent.943 944 :rtype: str945 """946 return f"{name}/{__version__}"947 948 887-def default_headers():949+def default_headers() -> CaseInsensitiveDict[str]:950 """951 :rtype: requests.structures.CaseInsensitiveDict952 """953 return CaseInsensitiveDict(5 unmodified lines959 }960 )961 962 901-def parse_header_links(value):963+def parse_header_links(value: str) -> list[dict[str, str]]:964 """Return a list of parsed link headers proxies.965 966 i.e. Link: <http:/.../front.jpeg>; rel=front; type="image/jpeg",<http://.../back.jpeg>; rel=back;type="image/jpeg"967 968 :rtype: list969 """970 909- links = []971+ links: list[dict[str, str]] = []972 973 replace_chars = " '\""974 975 value = value.strip(replace_chars)5 unmodified lines981 url, params = val.split(";", 1)982 except ValueError:983 url, params = val, ""984 923- link = {"url": url.strip("<> '\"")}985+ link: dict[str, str] = {"url": url.strip("<> '\"")}986 987 for param in params.split(";"):988 try:989 key, value = param.split("=")12 unmodified lines1002 _null2 = _null * 21003 _null3 = _null * 31004 1005 944-def guess_json_utf(data):1006+def guess_json_utf(data: bytes) -> str | None:1007 """1008 :rtype: str1009 """1010 # JSON always starts with two ASCII characters, so detection is as23 unmodified lines1034 # Did not detect a valid UTF-32 ascii-range character1035 return None1036 1037 976-def prepend_scheme_if_needed(url, new_scheme):1038+def 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.1041 1042 :rtype: str1043 """1044 parsed = parse_url(url)983- scheme, auth, host, port, path, query, fragment = parsed1045+ scheme, auth, _host, _port, path, query, fragment = parsed1046 1047 # 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 is4 unmodified lines1054 1055 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 line1064 1065 return urlunparse((scheme, netloc, path, "", query, fragment))1066 1067 1005-def get_auth_from_url(url):1068+def get_auth_from_url(url: str) -> tuple[str, str]:1069 """Given a url with authentication components, extract them into a tuple of1070 username,password.1071 1072 :rtype: (str,str)1073 """1074 parsed = urlparse(url)1075 1076 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 = ("", "")1081 1082 return auth1083 1084 1021-def check_header_validity(header):1085+def 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.1088 1089 :param header: tuple, in the format (name, value).2 unmodified lines1092 _validate_header_part(header, name, 0)1093 _validate_header_part(header, value, 1)1094 1095 1032-def _validate_header_part(header, header_part, header_validator_index):1096+def _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 )1111 1043- 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 )1118 1119 1051-def urldefragauth(url):1120+def urldefragauth(url: str) -> str:1121 """1122 Given a url remove the fragment and the authentication part.1123 1124 :rtype: str1125 """1057- scheme, netloc, path, params, query, fragment = urlparse(url)1126+ scheme, netloc, path, params, query, _fragment = urlparse(url)1127 1128 # see func:`prepend_scheme_if_needed`1129 if not netloc:1130 netloc, path = path, netloc2 unmodified lines1133 1134 return urlunparse((scheme, netloc, path, params, query, ""))1135 1136 1068-def rewind_body(prepared_request):1137+def 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 linesmodified:tests/test_requests.py+1 added
2577 unmodified lines2578 2579 def build_response(self):2580 request = self.calls[-1].args[0]2581 r = requests.Response()2582+ r.url = request.url2583 2584 try:2585 r.status_code = int(self.redirects.pop(0))2586 except IndexError:467 unmodified linesmodified:pyproject.toml+9 added
62 unmodified lines63 "pytest-xdist",64 "pytest>=3",65 "trustme",66 ]67+typecheck = [68+ "pyright",69+ "typing_extensions",70+]71 72 [tool.setuptools]73 license-files = ["LICENSE", "NOTICE"]74 32 unmodified lines107 addopts = "--doctest-modules"108 doctest_optionflags = "NORMALIZE_WHITESPACE ELLIPSIS"109 minversion = "6.2"110 testpaths = ["tests"]111+112+113+[tool.pyright]114+include = ["src/requests"]115+typeCheckingMode = "strict"