Skip to content
Myr

Move to src directory (#6506)

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 e9fa2e2 · Browse files · 40 files+5437 added−5440 removed
This commit

State

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

Diff stats

40 files+5437 added−5440 removed

  • other:+5437 added−5440 removed

40 files+5437 added−5440 removed

deleted:requests/__init__.py-180 removed
1# __2# /__) _ _ _ _ _/ _3# / ( (- (/ (/ (- _) / _)4# /56"""7Requests HTTP Library8~~~~~~~~~~~~~~~~~~~~~910Requests is an HTTP library, written in Python, for human beings.11Basic GET usage:1213 >>> import requests14 >>> r = requests.get('https://www.python.org')15 >>> r.status_code16 20017 >>> b'Python is a programming language' in r.content18 True1920... or POST:2122 >>> payload = dict(key1='value1', key2='value2')23 >>> r = requests.post('https://httpbin.org/post', data=payload)24 >>> print(r.text)25 {26 ...27 "form": {28 "key1": "value1",29 "key2": "value2"30 },31 ...32 }3334The other HTTP methods are supported - see `requests.api`. Full documentation35is at <https://requests.readthedocs.io>.3637:copyright: (c) 2017 by Kenneth Reitz.38:license: Apache 2.0, see LICENSE for more details.39"""4041import warnings4243import urllib34445from .exceptions import RequestsDependencyWarning4647try:48 from charset_normalizer import __version__ as charset_normalizer_version49except ImportError:50 charset_normalizer_version = None5152try:53 from chardet import __version__ as chardet_version54except ImportError:55 chardet_version = None565758def check_compatibility(urllib3_version, chardet_version, charset_normalizer_version):59 urllib3_version = urllib3_version.split(".")60 assert urllib3_version != ["dev"] # Verify urllib3 isn't installed from git.6162 # Sometimes, urllib3 only reports its version as 16.1.63 if len(urllib3_version) == 2:64 urllib3_version.append("0")6566 # Check urllib3 for compatibility.67 major, minor, patch = urllib3_version # noqa: F81168 major, minor, patch = int(major), int(minor), int(patch)69 # urllib3 >= 1.21.170 assert major >= 171 if major == 1:72 assert minor >= 217374 # Check charset_normalizer for compatibility.75 if chardet_version:76 major, minor, patch = chardet_version.split(".")[:3]77 major, minor, patch = int(major), int(minor), int(patch)78 # chardet_version >= 3.0.2, < 6.0.079 assert (3, 0, 2) <= (major, minor, patch) < (6, 0, 0)80 elif charset_normalizer_version:81 major, minor, patch = charset_normalizer_version.split(".")[:3]82 major, minor, patch = int(major), int(minor), int(patch)83 # charset_normalizer >= 2.0.0 < 4.0.084 assert (2, 0, 0) <= (major, minor, patch) < (4, 0, 0)85 else:86 raise Exception("You need either charset_normalizer or chardet installed")878889def _check_cryptography(cryptography_version):90 # cryptography < 1.3.491 try:92 cryptography_version = list(map(int, cryptography_version.split(".")))93 except ValueError:94 return9596 if cryptography_version < [1, 3, 4]:97 warning = "Old version of cryptography ({}) may cause slowdown.".format(98 cryptography_version99 )100 warnings.warn(warning, RequestsDependencyWarning)101102103# Check imported dependencies for compatibility.104try:105 check_compatibility(106 urllib3.__version__, chardet_version, charset_normalizer_version107 )108except (AssertionError, ValueError):109 warnings.warn(110 "urllib3 ({}) or chardet ({})/charset_normalizer ({}) doesn't match a supported "111 "version!".format(112 urllib3.__version__, chardet_version, charset_normalizer_version113 ),114 RequestsDependencyWarning,115 )116117# Attempt to enable urllib3's fallback for SNI support118# if the standard library doesn't support SNI or the119# 'ssl' library isn't available.120try:121 try:122 import ssl123 except ImportError:124 ssl = None125126 if not getattr(ssl, "HAS_SNI", False):127 from urllib3.contrib import pyopenssl128129 pyopenssl.inject_into_urllib3()130131 # Check cryptography version132 from cryptography import __version__ as cryptography_version133134 _check_cryptography(cryptography_version)135except ImportError:136 pass137138# urllib3's DependencyWarnings should be silenced.139from urllib3.exceptions import DependencyWarning140141warnings.simplefilter("ignore", DependencyWarning)142143# Set default logging handler to avoid "No handler found" warnings.144import logging145from logging import NullHandler146147from . import packages, utils148from .__version__ import (149 __author__,150 __author_email__,151 __build__,152 __cake__,153 __copyright__,154 __description__,155 __license__,156 __title__,157 __url__,158 __version__,159)160from .api import delete, get, head, options, patch, post, put, request161from .exceptions import (162 ConnectionError,163 ConnectTimeout,164 FileModeWarning,165 HTTPError,166 JSONDecodeError,167 ReadTimeout,168 RequestException,169 Timeout,170 TooManyRedirects,171 URLRequired,172)173from .models import PreparedRequest, Request, Response174from .sessions import Session, session175from .status_codes import codes176177logging.getLogger(__name__).addHandler(NullHandler())178179# FileModeWarnings go off per the default.180warnings.simplefilter("default", FileModeWarning, append=True)
deleted:requests/__version__.py-14 removed
1# .-. .-. .-. . . .-. .-. .-. .-.2# |( |- |.| | | |- `-. | `-.3# ' ' `-' `-`.`-' `-' `-' ' `-'45__title__ = "requests"6__description__ = "Python HTTP for Humans."7__url__ = "https://requests.readthedocs.io"8__version__ = "2.31.0"9__build__ = 0x02310010__author__ = "Kenneth Reitz"11__author_email__ = "me@kennethreitz.org"12__license__ = "Apache-2.0"13__copyright__ = "Copyright Kenneth Reitz"14__cake__ = "\u2728 \U0001f370 \u2728"
deleted:requests/_internal_utils.py-50 removed
1"""2requests._internal_utils3~~~~~~~~~~~~~~45Provides utility functions that are consumed internally by Requests6which depend on extremely few external helpers (such as compat)7"""8import re910from .compat import builtin_str1112_VALID_HEADER_NAME_RE_BYTE = re.compile(rb"^[^:\s][^:\r\n]*$")13_VALID_HEADER_NAME_RE_STR = re.compile(r"^[^:\s][^:\r\n]*$")14_VALID_HEADER_VALUE_RE_BYTE = re.compile(rb"^\S[^\r\n]*$|^$")15_VALID_HEADER_VALUE_RE_STR = re.compile(r"^\S[^\r\n]*$|^$")1617_HEADER_VALIDATORS_STR = (_VALID_HEADER_NAME_RE_STR, _VALID_HEADER_VALUE_RE_STR)18_HEADER_VALIDATORS_BYTE = (_VALID_HEADER_NAME_RE_BYTE, _VALID_HEADER_VALUE_RE_BYTE)19HEADER_VALIDATORS = {20 bytes: _HEADER_VALIDATORS_BYTE,21 str: _HEADER_VALIDATORS_STR,22}232425def to_native_string(string, encoding="ascii"):26 """Given a string object, regardless of type, returns a representation of27 that string in the native string type, encoding and decoding where28 necessary. This assumes ASCII unless told otherwise.29 """30 if isinstance(string, builtin_str):31 out = string32 else:33 out = string.decode(encoding)3435 return out363738def unicode_is_ascii(u_string):39 """Determine if unicode string only contains ASCII characters.4041 :param str u_string: unicode string to check. Must be unicode42 and not Python 2 `str`.43 :rtype: bool44 """45 assert isinstance(u_string, str)46 try:47 u_string.encode("ascii")48 return True49 except UnicodeEncodeError:50 return False
deleted:requests/adapters.py-537 removed
1"""2requests.adapters3~~~~~~~~~~~~~~~~~45This module contains the transport adapters that Requests uses to define6and maintain connections.7"""89import os.path10import socket # noqa: F4011112from urllib3.exceptions import ClosedPoolError, ConnectTimeoutError13from urllib3.exceptions import HTTPError as _HTTPError14from urllib3.exceptions import InvalidHeader as _InvalidHeader15from urllib3.exceptions import (16 LocationValueError,17 MaxRetryError,18 NewConnectionError,19 ProtocolError,20)21from urllib3.exceptions import ProxyError as _ProxyError22from urllib3.exceptions import ReadTimeoutError, ResponseError23from urllib3.exceptions import SSLError as _SSLError24from urllib3.poolmanager import PoolManager, proxy_from_url25from urllib3.util import Timeout as TimeoutSauce26from urllib3.util import parse_url27from urllib3.util.retry import Retry2829from .auth import _basic_auth_str30from .compat import basestring, urlparse31from .cookies import extract_cookies_to_jar32from .exceptions import (33 ConnectionError,34 ConnectTimeout,35 InvalidHeader,36 InvalidProxyURL,37 InvalidSchema,38 InvalidURL,39 ProxyError,40 ReadTimeout,41 RetryError,42 SSLError,43)44from .models import Response45from .structures import CaseInsensitiveDict46from .utils import (47 DEFAULT_CA_BUNDLE_PATH,48 extract_zipped_paths,49 get_auth_from_url,50 get_encoding_from_headers,51 prepend_scheme_if_needed,52 select_proxy,53 urldefragauth,54)5556try:57 from urllib3.contrib.socks import SOCKSProxyManager58except ImportError:5960 def SOCKSProxyManager(*args, **kwargs):61 raise InvalidSchema("Missing dependencies for SOCKS support.")626364DEFAULT_POOLBLOCK = False65DEFAULT_POOLSIZE = 1066DEFAULT_RETRIES = 067DEFAULT_POOL_TIMEOUT = None686970class BaseAdapter:71 """The Base Transport Adapter"""7273 def __init__(self):74 super().__init__()7576 def send(77 self, request, stream=False, timeout=None, verify=True, cert=None, proxies=None78 ):79 """Sends PreparedRequest object. Returns Response object.8081 :param request: The :class:`PreparedRequest <PreparedRequest>` being sent.82 :param stream: (optional) Whether to stream the request content.83 :param timeout: (optional) How long to wait for the server to send84 data before giving up, as a float, or a :ref:`(connect timeout,85 read timeout) <timeouts>` tuple.86 :type timeout: float or tuple87 :param verify: (optional) Either a boolean, in which case it controls whether we verify88 the server's TLS certificate, or a string, in which case it must be a path89 to a CA bundle to use90 :param cert: (optional) Any user-provided SSL certificate to be trusted.91 :param proxies: (optional) The proxies dictionary to apply to the request.92 """93 raise NotImplementedError9495 def close(self):96 """Cleans up adapter specific items."""97 raise NotImplementedError9899100class HTTPAdapter(BaseAdapter):101 """The built-in HTTP Adapter for urllib3.102103 Provides a general-case interface for Requests sessions to contact HTTP and104 HTTPS urls by implementing the Transport Adapter interface. This class will105 usually be created by the :class:`Session <Session>` class under the106 covers.107108 :param pool_connections: The number of urllib3 connection pools to cache.109 :param pool_maxsize: The maximum number of connections to save in the pool.110 :param max_retries: The maximum number of retries each connection111 should attempt. Note, this applies only to failed DNS lookups, socket112 connections and connection timeouts, never to requests where data has113 made it to the server. By default, Requests does not retry failed114 connections. If you need granular control over the conditions under115 which we retry a request, import urllib3's ``Retry`` class and pass116 that instead.117 :param pool_block: Whether the connection pool should block for connections.118119 Usage::120121 >>> import requests122 >>> s = requests.Session()123 >>> a = requests.adapters.HTTPAdapter(max_retries=3)124 >>> s.mount('http://', a)125 """126127 __attrs__ = [128 "max_retries",129 "config",130 "_pool_connections",131 "_pool_maxsize",132 "_pool_block",133 ]134135 def __init__(136 self,137 pool_connections=DEFAULT_POOLSIZE,138 pool_maxsize=DEFAULT_POOLSIZE,139 max_retries=DEFAULT_RETRIES,140 pool_block=DEFAULT_POOLBLOCK,141 ):142 if max_retries == DEFAULT_RETRIES:143 self.max_retries = Retry(0, read=False)144 else:145 self.max_retries = Retry.from_int(max_retries)146 self.config = {}147 self.proxy_manager = {}148149 super().__init__()150151 self._pool_connections = pool_connections152 self._pool_maxsize = pool_maxsize153 self._pool_block = pool_block154155 self.init_poolmanager(pool_connections, pool_maxsize, block=pool_block)156157 def __getstate__(self):158 return {attr: getattr(self, attr, None) for attr in self.__attrs__}159160 def __setstate__(self, state):161 # Can't handle by adding 'proxy_manager' to self.__attrs__ because162 # self.poolmanager uses a lambda function, which isn't pickleable.163 self.proxy_manager = {}164 self.config = {}165166 for attr, value in state.items():167 setattr(self, attr, value)168169 self.init_poolmanager(170 self._pool_connections, self._pool_maxsize, block=self._pool_block171 )172173 def init_poolmanager(174 self, connections, maxsize, block=DEFAULT_POOLBLOCK, **pool_kwargs175 ):176 """Initializes a urllib3 PoolManager.177178 This method should not be called from user code, and is only179 exposed for use when subclassing the180 :class:`HTTPAdapter <requests.adapters.HTTPAdapter>`.181182 :param connections: The number of urllib3 connection pools to cache.183 :param maxsize: The maximum number of connections to save in the pool.184 :param block: Block when no free connections are available.185 :param pool_kwargs: Extra keyword arguments used to initialize the Pool Manager.186 """187 # save these values for pickling188 self._pool_connections = connections189 self._pool_maxsize = maxsize190 self._pool_block = block191192 self.poolmanager = PoolManager(193 num_pools=connections,194 maxsize=maxsize,195 block=block,196 **pool_kwargs,197 )198199 def proxy_manager_for(self, proxy, **proxy_kwargs):200 """Return urllib3 ProxyManager for the given proxy.201202 This method should not be called from user code, and is only203 exposed for use when subclassing the204 :class:`HTTPAdapter <requests.adapters.HTTPAdapter>`.205206 :param proxy: The proxy to return a urllib3 ProxyManager for.207 :param proxy_kwargs: Extra keyword arguments used to configure the Proxy Manager.208 :returns: ProxyManager209 :rtype: urllib3.ProxyManager210 """211 if proxy in self.proxy_manager:212 manager = self.proxy_manager[proxy]213 elif proxy.lower().startswith("socks"):214 username, password = get_auth_from_url(proxy)215 manager = self.proxy_manager[proxy] = SOCKSProxyManager(216 proxy,217 username=username,218 password=password,219 num_pools=self._pool_connections,220 maxsize=self._pool_maxsize,221 block=self._pool_block,222 **proxy_kwargs,223 )224 else:225 proxy_headers = self.proxy_headers(proxy)226 manager = self.proxy_manager[proxy] = proxy_from_url(227 proxy,228 proxy_headers=proxy_headers,229 num_pools=self._pool_connections,230 maxsize=self._pool_maxsize,231 block=self._pool_block,232 **proxy_kwargs,233 )234235 return manager236237 def cert_verify(self, conn, url, verify, cert):238 """Verify a SSL certificate. This method should not be called from user239 code, and is only exposed for use when subclassing the240 :class:`HTTPAdapter <requests.adapters.HTTPAdapter>`.241242 :param conn: The urllib3 connection object associated with the cert.243 :param url: The requested URL.244 :param verify: Either a boolean, in which case it controls whether we verify245 the server's TLS certificate, or a string, in which case it must be a path246 to a CA bundle to use247 :param cert: The SSL certificate to verify.248 """249 if url.lower().startswith("https") and verify:250 cert_loc = None251252 # Allow self-specified cert location.253 if verify is not True:254 cert_loc = verify255256 if not cert_loc:257 cert_loc = extract_zipped_paths(DEFAULT_CA_BUNDLE_PATH)258259 if not cert_loc or not os.path.exists(cert_loc):260 raise OSError(261 f"Could not find a suitable TLS CA certificate bundle, "262 f"invalid path: {cert_loc}"263 )264265 conn.cert_reqs = "CERT_REQUIRED"266267 if not os.path.isdir(cert_loc):268 conn.ca_certs = cert_loc269 else:270 conn.ca_cert_dir = cert_loc271 else:272 conn.cert_reqs = "CERT_NONE"273 conn.ca_certs = None274 conn.ca_cert_dir = None275276 if cert:277 if not isinstance(cert, basestring):278 conn.cert_file = cert[0]279 conn.key_file = cert[1]280 else:281 conn.cert_file = cert282 conn.key_file = None283 if conn.cert_file and not os.path.exists(conn.cert_file):284 raise OSError(285 f"Could not find the TLS certificate file, "286 f"invalid path: {conn.cert_file}"287 )288 if conn.key_file and not os.path.exists(conn.key_file):289 raise OSError(290 f"Could not find the TLS key file, invalid path: {conn.key_file}"291 )292293 def build_response(self, req, resp):294 """Builds a :class:`Response <requests.Response>` object from a urllib3295 response. This should not be called from user code, and is only exposed296 for use when subclassing the297 :class:`HTTPAdapter <requests.adapters.HTTPAdapter>`298299 :param req: The :class:`PreparedRequest <PreparedRequest>` used to generate the response.300 :param resp: The urllib3 response object.301 :rtype: requests.Response302 """303 response = Response()304305 # Fallback to None if there's no status_code, for whatever reason.306 response.status_code = getattr(resp, "status", None)307308 # Make headers case-insensitive.309 response.headers = CaseInsensitiveDict(getattr(resp, "headers", {}))310311 # Set encoding.312 response.encoding = get_encoding_from_headers(response.headers)313 response.raw = resp314 response.reason = response.raw.reason315316 if isinstance(req.url, bytes):317 response.url = req.url.decode("utf-8")318 else:319 response.url = req.url320321 # Add new cookies from the server.322 extract_cookies_to_jar(response.cookies, req, resp)323324 # Give the Response some context.325 response.request = req326 response.connection = self327328 return response329330 def get_connection(self, url, proxies=None):331 """Returns a urllib3 connection for the given URL. This should not be332 called from user code, and is only exposed for use when subclassing the333 :class:`HTTPAdapter <requests.adapters.HTTPAdapter>`.334335 :param url: The URL to connect to.336 :param proxies: (optional) A Requests-style dictionary of proxies used on this request.337 :rtype: urllib3.ConnectionPool338 """339 proxy = select_proxy(url, proxies)340341 if proxy:342 proxy = prepend_scheme_if_needed(proxy, "http")343 proxy_url = parse_url(proxy)344 if not proxy_url.host:345 raise InvalidProxyURL(346 "Please check proxy URL. It is malformed "347 "and could be missing the host."348 )349 proxy_manager = self.proxy_manager_for(proxy)350 conn = proxy_manager.connection_from_url(url)351 else:352 # Only scheme should be lower case353 parsed = urlparse(url)354 url = parsed.geturl()355 conn = self.poolmanager.connection_from_url(url)356357 return conn358359 def close(self):360 """Disposes of any internal state.361362 Currently, this closes the PoolManager and any active ProxyManager,363 which closes any pooled connections.364 """365 self.poolmanager.clear()366 for proxy in self.proxy_manager.values():367 proxy.clear()368369 def request_url(self, request, proxies):370 """Obtain the url to use when making the final request.371372 If the message is being sent through a HTTP proxy, the full URL has to373 be used. Otherwise, we should only use the path portion of the URL.374375 This should not be called from user code, and is only exposed for use376 when subclassing the377 :class:`HTTPAdapter <requests.adapters.HTTPAdapter>`.378379 :param request: The :class:`PreparedRequest <PreparedRequest>` being sent.380 :param proxies: A dictionary of schemes or schemes and hosts to proxy URLs.381 :rtype: str382 """383 proxy = select_proxy(request.url, proxies)384 scheme = urlparse(request.url).scheme385386 is_proxied_http_request = proxy and scheme != "https"387 using_socks_proxy = False388 if proxy:389 proxy_scheme = urlparse(proxy).scheme.lower()390 using_socks_proxy = proxy_scheme.startswith("socks")391392 url = request.path_url393 if is_proxied_http_request and not using_socks_proxy:394 url = urldefragauth(request.url)395396 return url397398 def add_headers(self, request, **kwargs):399 """Add any headers needed by the connection. As of v2.0 this does400 nothing by default, but is left for overriding by users that subclass401 the :class:`HTTPAdapter <requests.adapters.HTTPAdapter>`.402403 This should not be called from user code, and is only exposed for use404 when subclassing the405 :class:`HTTPAdapter <requests.adapters.HTTPAdapter>`.406407 :param request: The :class:`PreparedRequest <PreparedRequest>` to add headers to.408 :param kwargs: The keyword arguments from the call to send().409 """410 pass411412 def proxy_headers(self, proxy):413 """Returns a dictionary of the headers to add to any request sent414 through a proxy. This works with urllib3 magic to ensure that they are415 correctly sent to the proxy, rather than in a tunnelled request if416 CONNECT is being used.417418 This should not be called from user code, and is only exposed for use419 when subclassing the420 :class:`HTTPAdapter <requests.adapters.HTTPAdapter>`.421422 :param proxy: The url of the proxy being used for this request.423 :rtype: dict424 """425 headers = {}426 username, password = get_auth_from_url(proxy)427428 if username:429 headers["Proxy-Authorization"] = _basic_auth_str(username, password)430431 return headers432433 def send(434 self, request, stream=False, timeout=None, verify=True, cert=None, proxies=None435 ):436 """Sends PreparedRequest object. Returns Response object.437438 :param request: The :class:`PreparedRequest <PreparedRequest>` being sent.439 :param stream: (optional) Whether to stream the request content.440 :param timeout: (optional) How long to wait for the server to send441 data before giving up, as a float, or a :ref:`(connect timeout,442 read timeout) <timeouts>` tuple.443 :type timeout: float or tuple or urllib3 Timeout object444 :param verify: (optional) Either a boolean, in which case it controls whether445 we verify the server's TLS certificate, or a string, in which case it446 must be a path to a CA bundle to use447 :param cert: (optional) Any user-provided SSL certificate to be trusted.448 :param proxies: (optional) The proxies dictionary to apply to the request.449 :rtype: requests.Response450 """451452 try:453 conn = self.get_connection(request.url, proxies)454 except LocationValueError as e:455 raise InvalidURL(e, request=request)456457 self.cert_verify(conn, request.url, verify, cert)458 url = self.request_url(request, proxies)459 self.add_headers(460 request,461 stream=stream,462 timeout=timeout,463 verify=verify,464 cert=cert,465 proxies=proxies,466 )467468 chunked = not (request.body is None or "Content-Length" in request.headers)469470 if isinstance(timeout, tuple):471 try:472 connect, read = timeout473 timeout = TimeoutSauce(connect=connect, read=read)474 except ValueError:475 raise ValueError(476 f"Invalid timeout {timeout}. Pass a (connect, read) timeout tuple, "477 f"or a single float to set both timeouts to the same value."478 )479 elif isinstance(timeout, TimeoutSauce):480 pass481 else:482 timeout = TimeoutSauce(connect=timeout, read=timeout)483484 try:485 resp = conn.urlopen(486 method=request.method,487 url=url,488 body=request.body,489 headers=request.headers,490 redirect=False,491 assert_same_host=False,492 preload_content=False,493 decode_content=False,494 retries=self.max_retries,495 timeout=timeout,496 chunked=chunked,497 )498499 except (ProtocolError, OSError) as err:500 raise ConnectionError(err, request=request)501502 except MaxRetryError as e:503 if isinstance(e.reason, ConnectTimeoutError):504 # TODO: Remove this in 3.0.0: see #2811505 if not isinstance(e.reason, NewConnectionError):506 raise ConnectTimeout(e, request=request)507508 if isinstance(e.reason, ResponseError):509 raise RetryError(e, request=request)510511 if isinstance(e.reason, _ProxyError):512 raise ProxyError(e, request=request)513514 if isinstance(e.reason, _SSLError):515 # This branch is for urllib3 v1.22 and later.516 raise SSLError(e, request=request)517518 raise ConnectionError(e, request=request)519520 except ClosedPoolError as e:521 raise ConnectionError(e, request=request)522523 except _ProxyError as e:524 raise ProxyError(e)525526 except (_SSLError, _HTTPError) as e:527 if isinstance(e, _SSLError):528 # This branch is for urllib3 versions earlier than v1.22529 raise SSLError(e, request=request)530 elif isinstance(e, ReadTimeoutError):531 raise ReadTimeout(e, request=request)532 elif isinstance(e, _InvalidHeader):533 raise InvalidHeader(e, request=request)534 else:535 raise536537 return self.build_response(request, resp)
deleted:requests/api.py-157 removed
1"""2requests.api3~~~~~~~~~~~~45This module implements the Requests API.67:copyright: (c) 2012 by Kenneth Reitz.8:license: Apache2, see LICENSE for more details.9"""1011from . import sessions121314def request(method, url, **kwargs):15 """Constructs and sends a :class:`Request <Request>`.1617 :param method: method for the new :class:`Request` object: ``GET``, ``OPTIONS``, ``HEAD``, ``POST``, ``PUT``, ``PATCH``, or ``DELETE``.18 :param url: URL for the new :class:`Request` object.19 :param params: (optional) Dictionary, list of tuples or bytes to send20 in the query string for the :class:`Request`.21 :param data: (optional) Dictionary, list of tuples, bytes, or file-like22 object to send in the body of the :class:`Request`.23 :param json: (optional) A JSON serializable Python object to send in the body of the :class:`Request`.24 :param headers: (optional) Dictionary of HTTP Headers to send with the :class:`Request`.25 :param cookies: (optional) Dict or CookieJar object to send with the :class:`Request`.26 :param files: (optional) Dictionary of ``'name': file-like-objects`` (or ``{'name': file-tuple}``) for multipart encoding upload.27 ``file-tuple`` can be a 2-tuple ``('filename', fileobj)``, 3-tuple ``('filename', fileobj, 'content_type')``28 or a 4-tuple ``('filename', fileobj, 'content_type', custom_headers)``, where ``'content_type'`` is a string29 defining the content type of the given file and ``custom_headers`` a dict-like object containing additional headers30 to add for the file.31 :param auth: (optional) Auth tuple to enable Basic/Digest/Custom HTTP Auth.32 :param timeout: (optional) How many seconds to wait for the server to send data33 before giving up, as a float, or a :ref:`(connect timeout, read34 timeout) <timeouts>` tuple.35 :type timeout: float or tuple36 :param allow_redirects: (optional) Boolean. Enable/disable GET/OPTIONS/POST/PUT/PATCH/DELETE/HEAD redirection. Defaults to ``True``.37 :type allow_redirects: bool38 :param proxies: (optional) Dictionary mapping protocol to the URL of the proxy.39 :param verify: (optional) Either a boolean, in which case it controls whether we verify40 the server's TLS certificate, or a string, in which case it must be a path41 to a CA bundle to use. Defaults to ``True``.42 :param stream: (optional) if ``False``, the response content will be immediately downloaded.43 :param cert: (optional) if String, path to ssl client cert file (.pem). If Tuple, ('cert', 'key') pair.44 :return: :class:`Response <Response>` object45 :rtype: requests.Response4647 Usage::4849 >>> import requests50 >>> req = requests.request('GET', 'https://httpbin.org/get')51 >>> req52 <Response [200]>53 """5455 # By using the 'with' statement we are sure the session is closed, thus we56 # avoid leaving sockets open which can trigger a ResourceWarning in some57 # cases, and look like a memory leak in others.58 with sessions.Session() as session:59 return session.request(method=method, url=url, **kwargs)606162def get(url, params=None, **kwargs):63 r"""Sends a GET request.6465 :param url: URL for the new :class:`Request` object.66 :param params: (optional) Dictionary, list of tuples or bytes to send67 in the query string for the :class:`Request`.68 :param \*\*kwargs: Optional arguments that ``request`` takes.69 :return: :class:`Response <Response>` object70 :rtype: requests.Response71 """7273 return request("get", url, params=params, **kwargs)747576def options(url, **kwargs):77 r"""Sends an OPTIONS request.7879 :param url: URL for the new :class:`Request` object.80 :param \*\*kwargs: Optional arguments that ``request`` takes.81 :return: :class:`Response <Response>` object82 :rtype: requests.Response83 """8485 return request("options", url, **kwargs)868788def head(url, **kwargs):89 r"""Sends a HEAD request.9091 :param url: URL for the new :class:`Request` object.92 :param \*\*kwargs: Optional arguments that ``request`` takes. If93 `allow_redirects` is not provided, it will be set to `False` (as94 opposed to the default :meth:`request` behavior).95 :return: :class:`Response <Response>` object96 :rtype: requests.Response97 """9899 kwargs.setdefault("allow_redirects", False)100 return request("head", url, **kwargs)101102103def post(url, data=None, json=None, **kwargs):104 r"""Sends a POST request.105106 :param url: URL for the new :class:`Request` object.107 :param data: (optional) Dictionary, list of tuples, bytes, or file-like108 object to send in the body of the :class:`Request`.109 :param json: (optional) A JSON serializable Python object to send in the body of the :class:`Request`.110 :param \*\*kwargs: Optional arguments that ``request`` takes.111 :return: :class:`Response <Response>` object112 :rtype: requests.Response113 """114115 return request("post", url, data=data, json=json, **kwargs)116117118def put(url, data=None, **kwargs):119 r"""Sends a PUT request.120121 :param url: URL for the new :class:`Request` object.122 :param data: (optional) Dictionary, list of tuples, bytes, or file-like123 object to send in the body of the :class:`Request`.124 :param json: (optional) A JSON serializable Python object to send in the body of the :class:`Request`.125 :param \*\*kwargs: Optional arguments that ``request`` takes.126 :return: :class:`Response <Response>` object127 :rtype: requests.Response128 """129130 return request("put", url, data=data, **kwargs)131132133def patch(url, data=None, **kwargs):134 r"""Sends a PATCH request.135136 :param url: URL for the new :class:`Request` object.137 :param data: (optional) Dictionary, list of tuples, bytes, or file-like138 object to send in the body of the :class:`Request`.139 :param json: (optional) A JSON serializable Python object to send in the body of the :class:`Request`.140 :param \*\*kwargs: Optional arguments that ``request`` takes.141 :return: :class:`Response <Response>` object142 :rtype: requests.Response143 """144145 return request("patch", url, data=data, **kwargs)146147148def delete(url, **kwargs):149 r"""Sends a DELETE request.150151 :param url: URL for the new :class:`Request` object.152 :param \*\*kwargs: Optional arguments that ``request`` takes.153 :return: :class:`Response <Response>` object154 :rtype: requests.Response155 """156157 return request("delete", url, **kwargs)
deleted:requests/auth.py-314 removed
1"""2requests.auth3~~~~~~~~~~~~~45This module contains the authentication handlers for Requests.6"""78import hashlib9import os10import re11import threading12import time13import warnings14from base64 import b64encode1516from ._internal_utils import to_native_string17from .compat import basestring, str, urlparse18from .cookies import extract_cookies_to_jar19from .utils import parse_dict_header2021CONTENT_TYPE_FORM_URLENCODED = "application/x-www-form-urlencoded"22CONTENT_TYPE_MULTI_PART = "multipart/form-data"232425def _basic_auth_str(username, password):26 """Returns a Basic Auth string."""2728 # "I want us to put a big-ol' comment on top of it that29 # says that this behaviour is dumb but we need to preserve30 # it because people are relying on it."31 # - Lukasa32 #33 # These are here solely to maintain backwards compatibility34 # for things like ints. This will be removed in 3.0.0.35 if not isinstance(username, basestring):36 warnings.warn(37 "Non-string usernames will no longer be supported in Requests "38 "3.0.0. Please convert the object you've passed in ({!r}) to "39 "a string or bytes object in the near future to avoid "40 "problems.".format(username),41 category=DeprecationWarning,42 )43 username = str(username)4445 if not isinstance(password, basestring):46 warnings.warn(47 "Non-string passwords will no longer be supported in Requests "48 "3.0.0. Please convert the object you've passed in ({!r}) to "49 "a string or bytes object in the near future to avoid "50 "problems.".format(type(password)),51 category=DeprecationWarning,52 )53 password = str(password)54 # -- End Removal --5556 if isinstance(username, str):57 username = username.encode("latin1")5859 if isinstance(password, str):60 password = password.encode("latin1")6162 authstr = "Basic " + to_native_string(63 b64encode(b":".join((username, password))).strip()64 )6566 return authstr676869class AuthBase:70 """Base class that all auth implementations derive from"""7172 def __call__(self, r):73 raise NotImplementedError("Auth hooks must be callable.")747576class HTTPBasicAuth(AuthBase):77 """Attaches HTTP Basic Authentication to the given Request object."""7879 def __init__(self, username, password):80 self.username = username81 self.password = password8283 def __eq__(self, other):84 return all(85 [86 self.username == getattr(other, "username", None),87 self.password == getattr(other, "password", None),88 ]89 )9091 def __ne__(self, other):92 return not self == other9394 def __call__(self, r):95 r.headers["Authorization"] = _basic_auth_str(self.username, self.password)96 return r979899class HTTPProxyAuth(HTTPBasicAuth):100 """Attaches HTTP Proxy Authentication to a given Request object."""101102 def __call__(self, r):103 r.headers["Proxy-Authorization"] = _basic_auth_str(self.username, self.password)104 return r105106107class HTTPDigestAuth(AuthBase):108 """Attaches HTTP Digest Authentication to the given Request object."""109110 def __init__(self, username, password):111 self.username = username112 self.password = password113 # Keep state in per-thread local storage114 self._thread_local = threading.local()115116 def init_per_thread_state(self):117 # Ensure state is initialized just once per-thread118 if not hasattr(self._thread_local, "init"):119 self._thread_local.init = True120 self._thread_local.last_nonce = ""121 self._thread_local.nonce_count = 0122 self._thread_local.chal = {}123 self._thread_local.pos = None124 self._thread_local.num_401_calls = None125126 def build_digest_header(self, method, url):127 """128 :rtype: str129 """130131 realm = self._thread_local.chal["realm"]132 nonce = self._thread_local.chal["nonce"]133 qop = self._thread_local.chal.get("qop")134 algorithm = self._thread_local.chal.get("algorithm")135 opaque = self._thread_local.chal.get("opaque")136 hash_utf8 = None137138 if algorithm is None:139 _algorithm = "MD5"140 else:141 _algorithm = algorithm.upper()142 # lambdas assume digest modules are imported at the top level143 if _algorithm == "MD5" or _algorithm == "MD5-SESS":144145 def md5_utf8(x):146 if isinstance(x, str):147 x = x.encode("utf-8")148 return hashlib.md5(x).hexdigest()149150 hash_utf8 = md5_utf8151 elif _algorithm == "SHA":152153 def sha_utf8(x):154 if isinstance(x, str):155 x = x.encode("utf-8")156 return hashlib.sha1(x).hexdigest()157158 hash_utf8 = sha_utf8159 elif _algorithm == "SHA-256":160161 def sha256_utf8(x):162 if isinstance(x, str):163 x = x.encode("utf-8")164 return hashlib.sha256(x).hexdigest()165166 hash_utf8 = sha256_utf8167 elif _algorithm == "SHA-512":168169 def sha512_utf8(x):170 if isinstance(x, str):171 x = x.encode("utf-8")172 return hashlib.sha512(x).hexdigest()173174 hash_utf8 = sha512_utf8175176 KD = lambda s, d: hash_utf8(f"{s}:{d}") # noqa:E731177178 if hash_utf8 is None:179 return None180181 # XXX not implemented yet182 entdig = None183 p_parsed = urlparse(url)184 #: path is request-uri defined in RFC 2616 which should not be empty185 path = p_parsed.path or "/"186 if p_parsed.query:187 path += f"?{p_parsed.query}"188189 A1 = f"{self.username}:{realm}:{self.password}"190 A2 = f"{method}:{path}"191192 HA1 = hash_utf8(A1)193 HA2 = hash_utf8(A2)194195 if nonce == self._thread_local.last_nonce:196 self._thread_local.nonce_count += 1197 else:198 self._thread_local.nonce_count = 1199 ncvalue = f"{self._thread_local.nonce_count:08x}"200 s = str(self._thread_local.nonce_count).encode("utf-8")201 s += nonce.encode("utf-8")202 s += time.ctime().encode("utf-8")203 s += os.urandom(8)204205 cnonce = hashlib.sha1(s).hexdigest()[:16]206 if _algorithm == "MD5-SESS":207 HA1 = hash_utf8(f"{HA1}:{nonce}:{cnonce}")208209 if not qop:210 respdig = KD(HA1, f"{nonce}:{HA2}")211 elif qop == "auth" or "auth" in qop.split(","):212 noncebit = f"{nonce}:{ncvalue}:{cnonce}:auth:{HA2}"213 respdig = KD(HA1, noncebit)214 else:215 # XXX handle auth-int.216 return None217218 self._thread_local.last_nonce = nonce219220 # XXX should the partial digests be encoded too?221 base = (222 f'username="{self.username}", realm="{realm}", nonce="{nonce}", '223 f'uri="{path}", response="{respdig}"'224 )225 if opaque:226 base += f', opaque="{opaque}"'227 if algorithm:228 base += f', algorithm="{algorithm}"'229 if entdig:230 base += f', digest="{entdig}"'231 if qop:232 base += f', qop="auth", nc={ncvalue}, cnonce="{cnonce}"'233234 return f"Digest {base}"235236 def handle_redirect(self, r, **kwargs):237 """Reset num_401_calls counter on redirects."""238 if r.is_redirect:239 self._thread_local.num_401_calls = 1240241 def handle_401(self, r, **kwargs):242 """243 Takes the given response and tries digest-auth, if needed.244245 :rtype: requests.Response246 """247248 # If response is not 4xx, do not auth249 # See https://github.com/psf/requests/issues/3772250 if not 400 <= r.status_code < 500:251 self._thread_local.num_401_calls = 1252 return r253254 if self._thread_local.pos is not None:255 # Rewind the file position indicator of the body to where256 # it was to resend the request.257 r.request.body.seek(self._thread_local.pos)258 s_auth = r.headers.get("www-authenticate", "")259260 if "digest" in s_auth.lower() and self._thread_local.num_401_calls < 2:261 self._thread_local.num_401_calls += 1262 pat = re.compile(r"digest ", flags=re.IGNORECASE)263 self._thread_local.chal = parse_dict_header(pat.sub("", s_auth, count=1))264265 # Consume content and release the original connection266 # to allow our new request to reuse the same one.267 r.content268 r.close()269 prep = r.request.copy()270 extract_cookies_to_jar(prep._cookies, r.request, r.raw)271 prep.prepare_cookies(prep._cookies)272273 prep.headers["Authorization"] = self.build_digest_header(274 prep.method, prep.url275 )276 _r = r.connection.send(prep, **kwargs)277 _r.history.append(r)278 _r.request = prep279280 return _r281282 self._thread_local.num_401_calls = 1283 return r284285 def __call__(self, r):286 # Initialize per-thread state, if needed287 self.init_per_thread_state()288 # If we have a saved nonce, skip the 401289 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:294 # In the case of HTTPDigestAuth being reused and the body of295 # the previous request was a file-like object, pos has the296 # file position of the previous body. Ensure it's set to297 # None.298 self._thread_local.pos = None299 r.register_hook("response", self.handle_401)300 r.register_hook("response", self.handle_redirect)301 self._thread_local.num_401_calls = 1302303 return r304305 def __eq__(self, other):306 return all(307 [308 self.username == getattr(other, "username", None),309 self.password == getattr(other, "password", None),310 ]311 )312313 def __ne__(self, other):314 return not self == other
deleted:requests/certs.py-17 removed
1#!/usr/bin/env python23"""4requests.certs5~~~~~~~~~~~~~~67This module returns the preferred default CA certificate bundle. There is8only one — the one from the certifi package.910If you are packaging Requests, e.g., for a Linux distribution or a managed11environment, you can change the definition of where() to return a separately12packaged CA bundle.13"""14from certifi import where1516if __name__ == "__main__":17 print(where())
deleted:requests/compat.py-79 removed
1"""2requests.compat3~~~~~~~~~~~~~~~45This module previously handled import compatibility issues6between Python 2 and Python 3. It remains for backwards7compatibility until the next major version.8"""910try:11 import chardet12except ImportError:13 import charset_normalizer as chardet1415import sys1617# -------18# Pythons19# -------2021# Syntax sugar.22_ver = sys.version_info2324#: Python 2.x?25is_py2 = _ver[0] == 22627#: Python 3.x?28is_py3 = _ver[0] == 32930# json/simplejson module import resolution31has_simplejson = False32try:33 import simplejson as json3435 has_simplejson = True36except ImportError:37 import json3839if has_simplejson:40 from simplejson import JSONDecodeError41else:42 from json import JSONDecodeError4344# Keep OrderedDict for backwards compatibility.45from collections import OrderedDict46from collections.abc import Callable, Mapping, MutableMapping47from http import cookiejar as cookielib48from http.cookies import Morsel49from io import StringIO5051# --------------52# Legacy Imports53# --------------54from urllib.parse import (55 quote,56 quote_plus,57 unquote,58 unquote_plus,59 urldefrag,60 urlencode,61 urljoin,62 urlparse,63 urlsplit,64 urlunparse,65)66from urllib.request import (67 getproxies,68 getproxies_environment,69 parse_http_list,70 proxy_bypass,71 proxy_bypass_environment,72)7374builtin_str = str75str = str76bytes = bytes77basestring = (str, bytes)78numeric_types = (int, float)79integer_types = (int,)
deleted:requests/cookies.py-561 removed
1"""2requests.cookies3~~~~~~~~~~~~~~~~45Compatibility code to be able to use `http.cookiejar.CookieJar` with requests.67requests.utils imports from here, so be careful with imports.8"""910import calendar11import copy12import time1314from ._internal_utils import to_native_string15from .compat import Morsel, MutableMapping, cookielib, urlparse, urlunparse1617try:18 import threading19except ImportError:20 import dummy_threading as threading212223class MockRequest:24 """Wraps a `requests.Request` to mimic a `urllib2.Request`.2526 The code in `http.cookiejar.CookieJar` expects this interface in order to correctly27 manage cookie policies, i.e., determine whether a cookie can be set, given the28 domains of the request and the cookie.2930 The original request object is read-only. The client is responsible for collecting31 the new headers via `get_new_headers()` and interpreting them appropriately. You32 probably want `get_cookie_header`, defined below.33 """3435 def __init__(self, request):36 self._r = request37 self._new_headers = {}38 self.type = urlparse(self._r.url).scheme3940 def get_type(self):41 return self.type4243 def get_host(self):44 return urlparse(self._r.url).netloc4546 def get_origin_req_host(self):47 return self.get_host()4849 def get_full_url(self):50 # Only return the response's URL if the user hadn't set the Host51 # header52 if not self._r.headers.get("Host"):53 return self._r.url54 # If they did set it, retrieve it and reconstruct the expected domain55 host = to_native_string(self._r.headers["Host"], encoding="utf-8")56 parsed = urlparse(self._r.url)57 # Reconstruct the URL as we expect it58 return urlunparse(59 [60 parsed.scheme,61 host,62 parsed.path,63 parsed.params,64 parsed.query,65 parsed.fragment,66 ]67 )6869 def is_unverifiable(self):70 return True7172 def has_header(self, name):73 return name in self._r.headers or name in self._new_headers7475 def get_header(self, name, default=None):76 return self._r.headers.get(name, self._new_headers.get(name, default))7778 def add_header(self, key, val):79 """cookiejar has no legitimate use for this method; add it back if you find one."""80 raise NotImplementedError(81 "Cookie headers should be added with add_unredirected_header()"82 )8384 def add_unredirected_header(self, name, value):85 self._new_headers[name] = value8687 def get_new_headers(self):88 return self._new_headers8990 @property91 def unverifiable(self):92 return self.is_unverifiable()9394 @property95 def origin_req_host(self):96 return self.get_origin_req_host()9798 @property99 def host(self):100 return self.get_host()101102103class MockResponse:104 """Wraps a `httplib.HTTPMessage` to mimic a `urllib.addinfourl`.105106 ...what? Basically, expose the parsed HTTP headers from the server response107 the way `http.cookiejar` expects to see them.108 """109110 def __init__(self, headers):111 """Make a MockResponse for `cookiejar` to read.112113 :param headers: a httplib.HTTPMessage or analogous carrying the headers114 """115 self._headers = headers116117 def info(self):118 return self._headers119120 def getheaders(self, name):121 self._headers.getheaders(name)122123124def extract_cookies_to_jar(jar, request, response):125 """Extract the cookies from the response into a CookieJar.126127 :param jar: http.cookiejar.CookieJar (not necessarily a RequestsCookieJar)128 :param request: our own requests.Request object129 :param response: urllib3.HTTPResponse object130 """131 if not (hasattr(response, "_original_response") and response._original_response):132 return133 # the _original_response field is the wrapped httplib.HTTPResponse object,134 req = MockRequest(request)135 # pull out the HTTPMessage with the headers and put it in the mock:136 res = MockResponse(response._original_response.msg)137 jar.extract_cookies(res, req)138139140def get_cookie_header(jar, request):141 """142 Produce an appropriate Cookie header string to be sent with `request`, or None.143144 :rtype: str145 """146 r = MockRequest(request)147 jar.add_cookie_header(r)148 return r.get_new_headers().get("Cookie")149150151def remove_cookie_by_name(cookiejar, name, domain=None, path=None):152 """Unsets a cookie by name, by default over all domains and paths.153154 Wraps CookieJar.clear(), is O(n).155 """156 clearables = []157 for cookie in cookiejar:158 if cookie.name != name:159 continue160 if domain is not None and domain != cookie.domain:161 continue162 if path is not None and path != cookie.path:163 continue164 clearables.append((cookie.domain, cookie.path, cookie.name))165166 for domain, path, name in clearables:167 cookiejar.clear(domain, path, name)168169170class CookieConflictError(RuntimeError):171 """There are two cookies that meet the criteria specified in the cookie jar.172 Use .get and .set and include domain and path args in order to be more specific.173 """174175176class RequestsCookieJar(cookielib.CookieJar, MutableMapping):177 """Compatibility class; is a http.cookiejar.CookieJar, but exposes a dict178 interface.179180 This is the CookieJar we create by default for requests and sessions that181 don't specify one, since some clients may expect response.cookies and182 session.cookies to support dict operations.183184 Requests does not use the dict interface internally; it's just for185 compatibility with external client code. All requests code should work186 out of the box with externally provided instances of ``CookieJar``, e.g.187 ``LWPCookieJar`` and ``FileCookieJar``.188189 Unlike a regular CookieJar, this class is pickleable.190191 .. warning:: dictionary operations that are normally O(1) may be O(n).192 """193194 def get(self, name, default=None, domain=None, path=None):195 """Dict-like get() that also supports optional domain and path args in196 order to resolve naming collisions from using one cookie jar over197 multiple domains.198199 .. warning:: operation is O(n), not O(1).200 """201 try:202 return self._find_no_duplicates(name, domain, path)203 except KeyError:204 return default205206 def set(self, name, value, **kwargs):207 """Dict-like set() that also supports optional domain and path args in208 order to resolve naming collisions from using one cookie jar over209 multiple domains.210 """211 # support client code that unsets cookies by assignment of a None value:212 if value is None:213 remove_cookie_by_name(214 self, name, domain=kwargs.get("domain"), path=kwargs.get("path")215 )216 return217218 if isinstance(value, Morsel):219 c = morsel_to_cookie(value)220 else:221 c = create_cookie(name, value, **kwargs)222 self.set_cookie(c)223 return c224225 def iterkeys(self):226 """Dict-like iterkeys() that returns an iterator of names of cookies227 from the jar.228229 .. seealso:: itervalues() and iteritems().230 """231 for cookie in iter(self):232 yield cookie.name233234 def keys(self):235 """Dict-like keys() that returns a list of names of cookies from the236 jar.237238 .. seealso:: values() and items().239 """240 return list(self.iterkeys())241242 def itervalues(self):243 """Dict-like itervalues() that returns an iterator of values of cookies244 from the jar.245246 .. seealso:: iterkeys() and iteritems().247 """248 for cookie in iter(self):249 yield cookie.value250251 def values(self):252 """Dict-like values() that returns a list of values of cookies from the253 jar.254255 .. seealso:: keys() and items().256 """257 return list(self.itervalues())258259 def iteritems(self):260 """Dict-like iteritems() that returns an iterator of name-value tuples261 from the jar.262263 .. seealso:: iterkeys() and itervalues().264 """265 for cookie in iter(self):266 yield cookie.name, cookie.value267268 def items(self):269 """Dict-like items() that returns a list of name-value tuples from the270 jar. Allows client-code to call ``dict(RequestsCookieJar)`` and get a271 vanilla python dict of key value pairs.272273 .. seealso:: keys() and values().274 """275 return list(self.iteritems())276277 def list_domains(self):278 """Utility method to list all the domains in the jar."""279 domains = []280 for cookie in iter(self):281 if cookie.domain not in domains:282 domains.append(cookie.domain)283 return domains284285 def list_paths(self):286 """Utility method to list all the paths in the jar."""287 paths = []288 for cookie in iter(self):289 if cookie.path not in paths:290 paths.append(cookie.path)291 return paths292293 def multiple_domains(self):294 """Returns True if there are multiple domains in the jar.295 Returns False otherwise.296297 :rtype: bool298 """299 domains = []300 for cookie in iter(self):301 if cookie.domain is not None and cookie.domain in domains:302 return True303 domains.append(cookie.domain)304 return False # there is only one domain in jar305306 def get_dict(self, domain=None, path=None):307 """Takes as an argument an optional domain and path and returns a plain308 old Python dict of name-value pairs of cookies that meet the309 requirements.310311 :rtype: dict312 """313 dictionary = {}314 for cookie in iter(self):315 if (domain is None or cookie.domain == domain) and (316 path is None or cookie.path == path317 ):318 dictionary[cookie.name] = cookie.value319 return dictionary320321 def __contains__(self, name):322 try:323 return super().__contains__(name)324 except CookieConflictError:325 return True326327 def __getitem__(self, name):328 """Dict-like __getitem__() for compatibility with client code. Throws329 exception if there are more than one cookie with name. In that case,330 use the more explicit get() method instead.331332 .. warning:: operation is O(n), not O(1).333 """334 return self._find_no_duplicates(name)335336 def __setitem__(self, name, value):337 """Dict-like __setitem__ for compatibility with client code. Throws338 exception if there is already a cookie of that name in the jar. In that339 case, use the more explicit set() method instead.340 """341 self.set(name, value)342343 def __delitem__(self, name):344 """Deletes a cookie given a name. Wraps ``http.cookiejar.CookieJar``'s345 ``remove_cookie_by_name()``.346 """347 remove_cookie_by_name(self, name)348349 def set_cookie(self, cookie, *args, **kwargs):350 if (351 hasattr(cookie.value, "startswith")352 and cookie.value.startswith('"')353 and cookie.value.endswith('"')354 ):355 cookie.value = cookie.value.replace('\\"', "")356 return super().set_cookie(cookie, *args, **kwargs)357358 def update(self, other):359 """Updates this jar with cookies from another CookieJar or dict-like"""360 if isinstance(other, cookielib.CookieJar):361 for cookie in other:362 self.set_cookie(copy.copy(cookie))363 else:364 super().update(other)365366 def _find(self, name, domain=None, path=None):367 """Requests uses this method internally to get cookie values.368369 If there are conflicting cookies, _find arbitrarily chooses one.370 See _find_no_duplicates if you want an exception thrown if there are371 conflicting cookies.372373 :param name: a string containing name of cookie374 :param domain: (optional) string containing domain of cookie375 :param path: (optional) string containing path of cookie376 :return: cookie.value377 """378 for cookie in iter(self):379 if cookie.name == name:380 if domain is None or cookie.domain == domain:381 if path is None or cookie.path == path:382 return cookie.value383384 raise KeyError(f"name={name!r}, domain={domain!r}, path={path!r}")385386 def _find_no_duplicates(self, name, domain=None, path=None):387 """Both ``__get_item__`` and ``get`` call this function: it's never388 used elsewhere in Requests.389390 :param name: a string containing name of cookie391 :param domain: (optional) string containing domain of cookie392 :param path: (optional) string containing path of cookie393 :raises KeyError: if cookie is not found394 :raises CookieConflictError: if there are multiple cookies395 that match name and optionally domain and path396 :return: cookie.value397 """398 toReturn = None399 for cookie in iter(self):400 if cookie.name == name:401 if domain is None or cookie.domain == domain:402 if path is None or cookie.path == path:403 if toReturn is not None:404 # if there are multiple cookies that meet passed in criteria405 raise CookieConflictError(406 f"There are multiple cookies with name, {name!r}"407 )408 # we will eventually return this as long as no cookie conflict409 toReturn = cookie.value410411 if toReturn:412 return toReturn413 raise KeyError(f"name={name!r}, domain={domain!r}, path={path!r}")414415 def __getstate__(self):416 """Unlike a normal CookieJar, this class is pickleable."""417 state = self.__dict__.copy()418 # remove the unpickleable RLock object419 state.pop("_cookies_lock")420 return state421422 def __setstate__(self, state):423 """Unlike a normal CookieJar, this class is pickleable."""424 self.__dict__.update(state)425 if "_cookies_lock" not in self.__dict__:426 self._cookies_lock = threading.RLock()427428 def copy(self):429 """Return a copy of this RequestsCookieJar."""430 new_cj = RequestsCookieJar()431 new_cj.set_policy(self.get_policy())432 new_cj.update(self)433 return new_cj434435 def get_policy(self):436 """Return the CookiePolicy instance used."""437 return self._policy438439440def _copy_cookie_jar(jar):441 if jar is None:442 return None443444 if hasattr(jar, "copy"):445 # We're dealing with an instance of RequestsCookieJar446 return jar.copy()447 # We're dealing with a generic CookieJar instance448 new_jar = copy.copy(jar)449 new_jar.clear()450 for cookie in jar:451 new_jar.set_cookie(copy.copy(cookie))452 return new_jar453454455def create_cookie(name, value, **kwargs):456 """Make a cookie from underspecified parameters.457458 By default, the pair of `name` and `value` will be set for the domain ''459 and sent on every request (this is sometimes called a "supercookie").460 """461 result = {462 "version": 0,463 "name": name,464 "value": value,465 "port": None,466 "domain": "",467 "path": "/",468 "secure": False,469 "expires": None,470 "discard": True,471 "comment": None,472 "comment_url": None,473 "rest": {"HttpOnly": None},474 "rfc2109": False,475 }476477 badargs = set(kwargs) - set(result)478 if badargs:479 raise TypeError(480 f"create_cookie() got unexpected keyword arguments: {list(badargs)}"481 )482483 result.update(kwargs)484 result["port_specified"] = bool(result["port"])485 result["domain_specified"] = bool(result["domain"])486 result["domain_initial_dot"] = result["domain"].startswith(".")487 result["path_specified"] = bool(result["path"])488489 return cookielib.Cookie(**result)490491492def morsel_to_cookie(morsel):493 """Convert a Morsel object into a Cookie containing the one k/v pair."""494495 expires = None496 if morsel["max-age"]:497 try:498 expires = int(time.time() + int(morsel["max-age"]))499 except ValueError:500 raise TypeError(f"max-age: {morsel['max-age']} must be integer")501 elif morsel["expires"]:502 time_template = "%a, %d-%b-%Y %H:%M:%S GMT"503 expires = calendar.timegm(time.strptime(morsel["expires"], time_template))504 return create_cookie(505 comment=morsel["comment"],506 comment_url=bool(morsel["comment"]),507 discard=False,508 domain=morsel["domain"],509 expires=expires,510 name=morsel.key,511 path=morsel["path"],512 port=None,513 rest={"HttpOnly": morsel["httponly"]},514 rfc2109=False,515 secure=bool(morsel["secure"]),516 value=morsel.value,517 version=morsel["version"] or 0,518 )519520521def cookiejar_from_dict(cookie_dict, cookiejar=None, overwrite=True):522 """Returns a CookieJar from a key/value dictionary.523524 :param cookie_dict: Dict of key/values to insert into CookieJar.525 :param cookiejar: (optional) A cookiejar to add the cookies to.526 :param overwrite: (optional) If False, will not replace cookies527 already in the jar with new ones.528 :rtype: CookieJar529 """530 if cookiejar is None:531 cookiejar = RequestsCookieJar()532533 if cookie_dict is not None:534 names_from_jar = [cookie.name for cookie in cookiejar]535 for name in cookie_dict:536 if overwrite or (name not in names_from_jar):537 cookiejar.set_cookie(create_cookie(name, cookie_dict[name]))538539 return cookiejar540541542def merge_cookies(cookiejar, cookies):543 """Add cookies to cookiejar and returns a merged CookieJar.544545 :param cookiejar: CookieJar object to add the cookies to.546 :param cookies: Dictionary or CookieJar object to be added.547 :rtype: CookieJar548 """549 if not isinstance(cookiejar, cookielib.CookieJar):550 raise ValueError("You can only merge into CookieJar")551552 if isinstance(cookies, dict):553 cookiejar = cookiejar_from_dict(cookies, cookiejar=cookiejar, overwrite=False)554 elif isinstance(cookies, cookielib.CookieJar):555 try:556 cookiejar.update(cookies)557 except AttributeError:558 for cookie_in_jar in cookies:559 cookiejar.set_cookie(cookie_in_jar)560561 return cookiejar
deleted:requests/exceptions.py-141 removed
1"""2requests.exceptions3~~~~~~~~~~~~~~~~~~~45This module contains the set of Requests' exceptions.6"""7from urllib3.exceptions import HTTPError as BaseHTTPError89from .compat import JSONDecodeError as CompatJSONDecodeError101112class RequestException(IOError):13 """There was an ambiguous exception that occurred while handling your14 request.15 """1617 def __init__(self, *args, **kwargs):18 """Initialize RequestException with `request` and `response` objects."""19 response = kwargs.pop("response", None)20 self.response = response21 self.request = kwargs.pop("request", None)22 if response is not None and not self.request and hasattr(response, "request"):23 self.request = self.response.request24 super().__init__(*args, **kwargs)252627class InvalidJSONError(RequestException):28 """A JSON error occurred."""293031class JSONDecodeError(InvalidJSONError, CompatJSONDecodeError):32 """Couldn't decode the text into json"""3334 def __init__(self, *args, **kwargs):35 """36 Construct the JSONDecodeError instance first with all37 args. Then use it's args to construct the IOError so that38 the json specific args aren't used as IOError specific args39 and the error message from JSONDecodeError is preserved.40 """41 CompatJSONDecodeError.__init__(self, *args)42 InvalidJSONError.__init__(self, *self.args, **kwargs)434445class HTTPError(RequestException):46 """An HTTP error occurred."""474849class ConnectionError(RequestException):50 """A Connection error occurred."""515253class ProxyError(ConnectionError):54 """A proxy error occurred."""555657class SSLError(ConnectionError):58 """An SSL error occurred."""596061class Timeout(RequestException):62 """The request timed out.6364 Catching this error will catch both65 :exc:`~requests.exceptions.ConnectTimeout` and66 :exc:`~requests.exceptions.ReadTimeout` errors.67 """686970class ConnectTimeout(ConnectionError, Timeout):71 """The request timed out while trying to connect to the remote server.7273 Requests that produced this error are safe to retry.74 """757677class ReadTimeout(Timeout):78 """The server did not send any data in the allotted amount of time."""798081class URLRequired(RequestException):82 """A valid URL is required to make a request."""838485class TooManyRedirects(RequestException):86 """Too many redirects."""878889class MissingSchema(RequestException, ValueError):90 """The URL scheme (e.g. http or https) is missing."""919293class InvalidSchema(RequestException, ValueError):94 """The URL scheme provided is either invalid or unsupported."""959697class InvalidURL(RequestException, ValueError):98 """The URL provided was somehow invalid."""99100101class InvalidHeader(RequestException, ValueError):102 """The header value provided was somehow invalid."""103104105class InvalidProxyURL(InvalidURL):106 """The proxy URL provided is invalid."""107108109class ChunkedEncodingError(RequestException):110 """The server declared chunked encoding but sent an invalid chunk."""111112113class ContentDecodingError(RequestException, BaseHTTPError):114 """Failed to decode response content."""115116117class StreamConsumedError(RequestException, TypeError):118 """The content for this response was already consumed."""119120121class RetryError(RequestException):122 """Custom retries logic failed"""123124125class UnrewindableBodyError(RequestException):126 """Requests encountered an error when trying to rewind a body."""127128129# Warnings130131132class RequestsWarning(Warning):133 """Base warning for Requests."""134135136class FileModeWarning(RequestsWarning, DeprecationWarning):137 """A file was opened in text mode, but Requests determined its binary length."""138139140class RequestsDependencyWarning(RequestsWarning):141 """An imported dependency doesn't match the expected version range."""
deleted:requests/help.py-134 removed
1"""Module containing bug report helper(s)."""23import json4import platform5import ssl6import sys78import idna9import urllib31011from . import __version__ as requests_version1213try:14 import charset_normalizer15except ImportError:16 charset_normalizer = None1718try:19 import chardet20except ImportError:21 chardet = None2223try:24 from urllib3.contrib import pyopenssl25except ImportError:26 pyopenssl = None27 OpenSSL = None28 cryptography = None29else:30 import cryptography31 import OpenSSL323334def _implementation():35 """Return a dict with the Python implementation and version.3637 Provide both the name and the version of the Python implementation38 currently running. For example, on CPython 3.10.3 it will return39 {'name': 'CPython', 'version': '3.10.3'}.4041 This function works best on CPython and PyPy: in particular, it probably42 doesn't work for Jython or IronPython. Future investigation should be done43 to work out the correct shape of the code for those platforms.44 """45 implementation = platform.python_implementation()4647 if implementation == "CPython":48 implementation_version = platform.python_version()49 elif implementation == "PyPy":50 implementation_version = "{}.{}.{}".format(51 sys.pypy_version_info.major,52 sys.pypy_version_info.minor,53 sys.pypy_version_info.micro,54 )55 if sys.pypy_version_info.releaselevel != "final":56 implementation_version = "".join(57 [implementation_version, sys.pypy_version_info.releaselevel]58 )59 elif implementation == "Jython":60 implementation_version = platform.python_version() # Complete Guess61 elif implementation == "IronPython":62 implementation_version = platform.python_version() # Complete Guess63 else:64 implementation_version = "Unknown"6566 return {"name": implementation, "version": implementation_version}676869def info():70 """Generate information for a bug report."""71 try:72 platform_info = {73 "system": platform.system(),74 "release": platform.release(),75 }76 except OSError:77 platform_info = {78 "system": "Unknown",79 "release": "Unknown",80 }8182 implementation_info = _implementation()83 urllib3_info = {"version": urllib3.__version__}84 charset_normalizer_info = {"version": None}85 chardet_info = {"version": None}86 if charset_normalizer:87 charset_normalizer_info = {"version": charset_normalizer.__version__}88 if chardet:89 chardet_info = {"version": chardet.__version__}9091 pyopenssl_info = {92 "version": None,93 "openssl_version": "",94 }95 if OpenSSL:96 pyopenssl_info = {97 "version": OpenSSL.__version__,98 "openssl_version": f"{OpenSSL.SSL.OPENSSL_VERSION_NUMBER:x}",99 }100 cryptography_info = {101 "version": getattr(cryptography, "__version__", ""),102 }103 idna_info = {104 "version": getattr(idna, "__version__", ""),105 }106107 system_ssl = ssl.OPENSSL_VERSION_NUMBER108 system_ssl_info = {"version": f"{system_ssl:x}" if system_ssl is not None else ""}109110 return {111 "platform": platform_info,112 "implementation": implementation_info,113 "system_ssl": system_ssl_info,114 "using_pyopenssl": pyopenssl is not None,115 "using_charset_normalizer": chardet is None,116 "pyOpenSSL": pyopenssl_info,117 "urllib3": urllib3_info,118 "chardet": chardet_info,119 "charset_normalizer": charset_normalizer_info,120 "cryptography": cryptography_info,121 "idna": idna_info,122 "requests": {123 "version": requests_version,124 },125 }126127128def main():129 """Pretty-print the bug information as JSON."""130 print(json.dumps(info(), sort_keys=True, indent=2))131132133if __name__ == "__main__":134 main()
deleted:requests/hooks.py-33 removed
1"""2requests.hooks3~~~~~~~~~~~~~~45This module provides the capabilities for the Requests hooks system.67Available hooks:89``response``:10 The response generated from a Request.11"""12HOOKS = ["response"]131415def default_hooks():16 return {event: [] for event in HOOKS}171819# TODO: response is the only one202122def dispatch_hook(key, hooks, hook_data, **kwargs):23 """Dispatches a hook dictionary on a given piece of data."""24 hooks = hooks or {}25 hooks = hooks.get(key)26 if hooks:27 if hasattr(hooks, "__call__"):28 hooks = [hooks]29 for hook in hooks:30 _hook_data = hook(hook_data, **kwargs)31 if _hook_data is not None:32 hook_data = _hook_data33 return hook_data
deleted:requests/models.py-1032 removed
1"""2requests.models3~~~~~~~~~~~~~~~45This module contains the primary objects that power Requests.6"""78import datetime910# Import encoding now, to avoid implicit import later.11# Implicit import within threads may cause LookupError when standard library is in a ZIP,12# such as in Embedded Python. See https://github.com/psf/requests/issues/3578.13import encodings.idna # noqa: F40114from io import UnsupportedOperation1516from urllib3.exceptions import (17 DecodeError,18 LocationParseError,19 ProtocolError,20 ReadTimeoutError,21 SSLError,22)23from urllib3.fields import RequestField24from urllib3.filepost import encode_multipart_formdata25from urllib3.util import parse_url2627from ._internal_utils import to_native_string, unicode_is_ascii28from .auth import HTTPBasicAuth29from .compat import (30 Callable,31 JSONDecodeError,32 Mapping,33 basestring,34 builtin_str,35 chardet,36 cookielib,37)38from .compat import json as complexjson39from .compat import urlencode, urlsplit, urlunparse40from .cookies import _copy_cookie_jar, cookiejar_from_dict, get_cookie_header41from .exceptions import (42 ChunkedEncodingError,43 ConnectionError,44 ContentDecodingError,45 HTTPError,46 InvalidJSONError,47 InvalidURL,48)49from .exceptions import JSONDecodeError as RequestsJSONDecodeError50from .exceptions import MissingSchema51from .exceptions import SSLError as RequestsSSLError52from .exceptions import StreamConsumedError53from .hooks import default_hooks54from .status_codes import codes55from .structures import CaseInsensitiveDict56from .utils import (57 check_header_validity,58 get_auth_from_url,59 guess_filename,60 guess_json_utf,61 iter_slices,62 parse_header_links,63 requote_uri,64 stream_decode_response_unicode,65 super_len,66 to_key_val_list,67)6869#: The set of HTTP status codes that indicate an automatically70#: processable redirect.71REDIRECT_STATI = (72 codes.moved, # 30173 codes.found, # 30274 codes.other, # 30375 codes.temporary_redirect, # 30776 codes.permanent_redirect, # 30877)7879DEFAULT_REDIRECT_LIMIT = 3080CONTENT_CHUNK_SIZE = 10 * 102481ITER_CHUNK_SIZE = 512828384class RequestEncodingMixin:85 @property86 def path_url(self):87 """Build the path URL to use."""8889 url = []9091 p = urlsplit(self.url)9293 path = p.path94 if not path:95 path = "/"9697 url.append(path)9899 query = p.query100 if query:101 url.append("?")102 url.append(query)103104 return "".join(url)105106 @staticmethod107 def _encode_params(data):108 """Encode parameters in a piece of data.109110 Will successfully encode parameters when passed as a dict or a list of111 2-tuples. Order is retained if data is a list of 2-tuples but arbitrary112 if parameters are supplied as a dict.113 """114115 if isinstance(data, (str, bytes)):116 return data117 elif hasattr(data, "read"):118 return data119 elif hasattr(data, "__iter__"):120 result = []121 for k, vs in to_key_val_list(data):122 if isinstance(vs, basestring) or not hasattr(vs, "__iter__"):123 vs = [vs]124 for v in vs:125 if v is not None:126 result.append(127 (128 k.encode("utf-8") if isinstance(k, str) else k,129 v.encode("utf-8") if isinstance(v, str) else v,130 )131 )132 return urlencode(result, doseq=True)133 else:134 return data135136 @staticmethod137 def _encode_files(files, data):138 """Build the body for a multipart/form-data request.139140 Will successfully encode files when passed as a dict or a list of141 tuples. Order is retained if data is a list of tuples but arbitrary142 if parameters are supplied as a dict.143 The tuples may be 2-tuples (filename, fileobj), 3-tuples (filename, fileobj, contentype)144 or 4-tuples (filename, fileobj, contentype, custom_headers).145 """146 if not files:147 raise ValueError("Files must be provided.")148 elif isinstance(data, basestring):149 raise ValueError("Data must not be a string.")150151 new_fields = []152 fields = to_key_val_list(data or {})153 files = to_key_val_list(files or {})154155 for field, val in fields:156 if isinstance(val, basestring) or not hasattr(val, "__iter__"):157 val = [val]158 for v in val:159 if v is not None:160 # Don't call str() on bytestrings: in Py3 it all goes wrong.161 if not isinstance(v, bytes):162 v = str(v)163164 new_fields.append(165 (166 field.decode("utf-8")167 if isinstance(field, bytes)168 else field,169 v.encode("utf-8") if isinstance(v, str) else v,170 )171 )172173 for k, v in files:174 # support for explicit filename175 ft = None176 fh = None177 if isinstance(v, (tuple, list)):178 if len(v) == 2:179 fn, fp = v180 elif len(v) == 3:181 fn, fp, ft = v182 else:183 fn, fp, ft, fh = v184 else:185 fn = guess_filename(v) or k186 fp = v187188 if isinstance(fp, (str, bytes, bytearray)):189 fdata = fp190 elif hasattr(fp, "read"):191 fdata = fp.read()192 elif fp is None:193 continue194 else:195 fdata = fp196197 rf = RequestField(name=k, data=fdata, filename=fn, headers=fh)198 rf.make_multipart(content_type=ft)199 new_fields.append(rf)200201 body, content_type = encode_multipart_formdata(new_fields)202203 return body, content_type204205206class RequestHooksMixin:207 def register_hook(self, event, hook):208 """Properly register a hook."""209210 if event not in self.hooks:211 raise ValueError(f'Unsupported event specified, with event name "{event}"')212213 if isinstance(hook, Callable):214 self.hooks[event].append(hook)215 elif hasattr(hook, "__iter__"):216 self.hooks[event].extend(h for h in hook if isinstance(h, Callable))217218 def deregister_hook(self, event, hook):219 """Deregister a previously registered hook.220 Returns True if the hook existed, False if not.221 """222223 try:224 self.hooks[event].remove(hook)225 return True226 except ValueError:227 return False228229230class Request(RequestHooksMixin):231 """A user-created :class:`Request <Request>` object.232233 Used to prepare a :class:`PreparedRequest <PreparedRequest>`, which is sent to the server.234235 :param method: HTTP method to use.236 :param url: URL to send.237 :param headers: dictionary of headers to send.238 :param files: dictionary of {filename: fileobject} files to multipart upload.239 :param data: the body to attach to the request. If a dictionary or240 list of tuples ``[(key, value)]`` is provided, form-encoding will241 take place.242 :param json: json for the body to attach to the request (if files or data is not specified).243 :param params: URL parameters to append to the URL. If a dictionary or244 list of tuples ``[(key, value)]`` is provided, form-encoding will245 take place.246 :param auth: Auth handler or (user, pass) tuple.247 :param cookies: dictionary or CookieJar of cookies to attach to this request.248 :param hooks: dictionary of callback hooks, for internal usage.249250 Usage::251252 >>> import requests253 >>> req = requests.Request('GET', 'https://httpbin.org/get')254 >>> req.prepare()255 <PreparedRequest [GET]>256 """257258 def __init__(259 self,260 method=None,261 url=None,262 headers=None,263 files=None,264 data=None,265 params=None,266 auth=None,267 cookies=None,268 hooks=None,269 json=None,270 ):271 # Default empty dicts for dict params.272 data = [] if data is None else data273 files = [] if files is None else files274 headers = {} if headers is None else headers275 params = {} if params is None else params276 hooks = {} if hooks is None else hooks277278 self.hooks = default_hooks()279 for k, v in list(hooks.items()):280 self.register_hook(event=k, hook=v)281282 self.method = method283 self.url = url284 self.headers = headers285 self.files = files286 self.data = data287 self.json = json288 self.params = params289 self.auth = auth290 self.cookies = cookies291292 def __repr__(self):293 return f"<Request [{self.method}]>"294295 def prepare(self):296 """Constructs a :class:`PreparedRequest <PreparedRequest>` for transmission and returns it."""297 p = PreparedRequest()298 p.prepare(299 method=self.method,300 url=self.url,301 headers=self.headers,302 files=self.files,303 data=self.data,304 json=self.json,305 params=self.params,306 auth=self.auth,307 cookies=self.cookies,308 hooks=self.hooks,309 )310 return p311312313class PreparedRequest(RequestEncodingMixin, RequestHooksMixin):314 """The fully mutable :class:`PreparedRequest <PreparedRequest>` object,315 containing the exact bytes that will be sent to the server.316317 Instances are generated from a :class:`Request <Request>` object, and318 should not be instantiated manually; doing so may produce undesirable319 effects.320321 Usage::322323 >>> import requests324 >>> req = requests.Request('GET', 'https://httpbin.org/get')325 >>> r = req.prepare()326 >>> r327 <PreparedRequest [GET]>328329 >>> s = requests.Session()330 >>> s.send(r)331 <Response [200]>332 """333334 def __init__(self):335 #: HTTP verb to send to the server.336 self.method = None337 #: HTTP URL to send the request to.338 self.url = None339 #: dictionary of HTTP headers.340 self.headers = None341 # The `CookieJar` used to create the Cookie header will be stored here342 # after prepare_cookies is called343 self._cookies = None344 #: request body to send to the server.345 self.body = None346 #: dictionary of callback hooks, for internal usage.347 self.hooks = default_hooks()348 #: integer denoting starting position of a readable file-like body.349 self._body_position = None350351 def prepare(352 self,353 method=None,354 url=None,355 headers=None,356 files=None,357 data=None,358 params=None,359 auth=None,360 cookies=None,361 hooks=None,362 json=None,363 ):364 """Prepares the entire request with the given parameters."""365366 self.prepare_method(method)367 self.prepare_url(url, params)368 self.prepare_headers(headers)369 self.prepare_cookies(cookies)370 self.prepare_body(data, files, json)371 self.prepare_auth(auth, url)372373 # Note that prepare_auth must be last to enable authentication schemes374 # such as OAuth to work on a fully prepared request.375376 # This MUST go after prepare_auth. Authenticators could add a hook377 self.prepare_hooks(hooks)378379 def __repr__(self):380 return f"<PreparedRequest [{self.method}]>"381382 def copy(self):383 p = PreparedRequest()384 p.method = self.method385 p.url = self.url386 p.headers = self.headers.copy() if self.headers is not None else None387 p._cookies = _copy_cookie_jar(self._cookies)388 p.body = self.body389 p.hooks = self.hooks390 p._body_position = self._body_position391 return p392393 def prepare_method(self, method):394 """Prepares the given HTTP method."""395 self.method = method396 if self.method is not None:397 self.method = to_native_string(self.method.upper())398399 @staticmethod400 def _get_idna_encoded_host(host):401 import idna402403 try:404 host = idna.encode(host, uts46=True).decode("utf-8")405 except idna.IDNAError:406 raise UnicodeError407 return host408409 def prepare_url(self, url, params):410 """Prepares the given HTTP URL."""411 #: Accept objects that have string representations.412 #: We're unable to blindly call unicode/str functions413 #: as this will include the bytestring indicator (b'')414 #: on python 3.x.415 #: https://github.com/psf/requests/pull/2238416 if isinstance(url, bytes):417 url = url.decode("utf8")418 else:419 url = str(url)420421 # Remove leading whitespaces from url422 url = url.lstrip()423424 # Don't do any URL preparation for non-HTTP schemes like `mailto`,425 # `data` etc to work around exceptions from `url_parse`, which426 # handles RFC 3986 only.427 if ":" in url and not url.lower().startswith("http"):428 self.url = url429 return430431 # Support for unicode domain names and paths.432 try:433 scheme, auth, host, port, path, query, fragment = parse_url(url)434 except LocationParseError as e:435 raise InvalidURL(*e.args)436437 if not scheme:438 raise MissingSchema(439 f"Invalid URL {url!r}: No scheme supplied. "440 f"Perhaps you meant https://{url}?"441 )442443 if not host:444 raise InvalidURL(f"Invalid URL {url!r}: No host supplied")445446 # In general, we want to try IDNA encoding the hostname if the string contains447 # non-ASCII characters. This allows users to automatically get the correct IDNA448 # behaviour. For strings containing only ASCII characters, we need to also verify449 # it doesn't start with a wildcard (*), before allowing the unencoded hostname.450 if not unicode_is_ascii(host):451 try:452 host = self._get_idna_encoded_host(host)453 except UnicodeError:454 raise InvalidURL("URL has an invalid label.")455 elif host.startswith(("*", ".")):456 raise InvalidURL("URL has an invalid label.")457458 # Carefully reconstruct the network location459 netloc = auth or ""460 if netloc:461 netloc += "@"462 netloc += host463 if port:464 netloc += f":{port}"465466 # Bare domains aren't valid URLs.467 if not path:468 path = "/"469470 if isinstance(params, (str, bytes)):471 params = to_native_string(params)472473 enc_params = self._encode_params(params)474 if enc_params:475 if query:476 query = f"{query}&{enc_params}"477 else:478 query = enc_params479480 url = requote_uri(urlunparse([scheme, netloc, path, None, query, fragment]))481 self.url = url482483 def prepare_headers(self, headers):484 """Prepares the given HTTP headers."""485486 self.headers = CaseInsensitiveDict()487 if headers:488 for header in headers.items():489 # Raise exception on invalid header value.490 check_header_validity(header)491 name, value = header492 self.headers[to_native_string(name)] = value493494 def prepare_body(self, data, files, json=None):495 """Prepares the given HTTP body data."""496497 # Check if file, fo, generator, iterator.498 # If not, run through normal process.499500 # Nottin' on you.501 body = None502 content_type = None503504 if not data and json is not None:505 # urllib3 requires a bytes-like body. Python 2's json.dumps506 # provides this natively, but Python 3 gives a Unicode string.507 content_type = "application/json"508509 try:510 body = complexjson.dumps(json, allow_nan=False)511 except ValueError as ve:512 raise InvalidJSONError(ve, request=self)513514 if not isinstance(body, bytes):515 body = body.encode("utf-8")516517 is_stream = all(518 [519 hasattr(data, "__iter__"),520 not isinstance(data, (basestring, list, tuple, Mapping)),521 ]522 )523524 if is_stream:525 try:526 length = super_len(data)527 except (TypeError, AttributeError, UnsupportedOperation):528 length = None529530 body = data531532 if getattr(body, "tell", None) is not None:533 # Record the current file position before reading.534 # This will allow us to rewind a file in the event535 # of a redirect.536 try:537 self._body_position = body.tell()538 except OSError:539 # This differentiates from None, allowing us to catch540 # a failed `tell()` later when trying to rewind the body541 self._body_position = object()542543 if files:544 raise NotImplementedError(545 "Streamed bodies and files are mutually exclusive."546 )547548 if length:549 self.headers["Content-Length"] = builtin_str(length)550 else:551 self.headers["Transfer-Encoding"] = "chunked"552 else:553 # Multi-part file uploads.554 if files:555 (body, content_type) = self._encode_files(files, data)556 else:557 if data:558 body = self._encode_params(data)559 if isinstance(data, basestring) or hasattr(data, "read"):560 content_type = None561 else:562 content_type = "application/x-www-form-urlencoded"563564 self.prepare_content_length(body)565566 # Add content-type if it wasn't explicitly provided.567 if content_type and ("content-type" not in self.headers):568 self.headers["Content-Type"] = content_type569570 self.body = body571572 def prepare_content_length(self, body):573 """Prepare Content-Length header based on request method and body"""574 if body is not None:575 length = super_len(body)576 if length:577 # If length exists, set it. Otherwise, we fallback578 # to Transfer-Encoding: chunked.579 self.headers["Content-Length"] = builtin_str(length)580 elif (581 self.method not in ("GET", "HEAD")582 and self.headers.get("Content-Length") is None583 ):584 # Set Content-Length to 0 for methods that can have a body585 # but don't provide one. (i.e. not GET or HEAD)586 self.headers["Content-Length"] = "0"587588 def prepare_auth(self, auth, url=""):589 """Prepares the given HTTP auth data."""590591 # If no Auth is explicitly provided, extract it from the URL first.592 if auth is None:593 url_auth = get_auth_from_url(self.url)594 auth = url_auth if any(url_auth) else None595596 if auth:597 if isinstance(auth, tuple) and len(auth) == 2:598 # special-case basic HTTP auth599 auth = HTTPBasicAuth(*auth)600601 # Allow auth to make its changes.602 r = auth(self)603604 # Update self to reflect the auth changes.605 self.__dict__.update(r.__dict__)606607 # Recompute Content-Length608 self.prepare_content_length(self.body)609610 def prepare_cookies(self, cookies):611 """Prepares the given HTTP cookie data.612613 This function eventually generates a ``Cookie`` header from the614 given cookies using cookielib. Due to cookielib's design, the header615 will not be regenerated if it already exists, meaning this function616 can only be called once for the life of the617 :class:`PreparedRequest <PreparedRequest>` object. Any subsequent calls618 to ``prepare_cookies`` will have no actual effect, unless the "Cookie"619 header is removed beforehand.620 """621 if isinstance(cookies, cookielib.CookieJar):622 self._cookies = cookies623 else:624 self._cookies = cookiejar_from_dict(cookies)625626 cookie_header = get_cookie_header(self._cookies, self)627 if cookie_header is not None:628 self.headers["Cookie"] = cookie_header629630 def prepare_hooks(self, hooks):631 """Prepares the given hooks."""632 # hooks can be passed as None to the prepare method and to this633 # method. To prevent iterating over None, simply use an empty list634 # if hooks is False-y635 hooks = hooks or []636 for event in hooks:637 self.register_hook(event, hooks[event])638639640class Response:641 """The :class:`Response <Response>` object, which contains a642 server's response to an HTTP request.643 """644645 __attrs__ = [646 "_content",647 "status_code",648 "headers",649 "url",650 "history",651 "encoding",652 "reason",653 "cookies",654 "elapsed",655 "request",656 ]657658 def __init__(self):659 self._content = False660 self._content_consumed = False661 self._next = None662663 #: Integer Code of responded HTTP Status, e.g. 404 or 200.664 self.status_code = None665666 #: Case-insensitive Dictionary of Response Headers.667 #: For example, ``headers['content-encoding']`` will return the668 #: value of a ``'Content-Encoding'`` response header.669 self.headers = CaseInsensitiveDict()670671 #: File-like object representation of response (for advanced usage).672 #: Use of ``raw`` requires that ``stream=True`` be set on the request.673 #: This requirement does not apply for use internally to Requests.674 self.raw = None675676 #: Final URL location of Response.677 self.url = None678679 #: Encoding to decode with when accessing r.text.680 self.encoding = None681682 #: A list of :class:`Response <Response>` objects from683 #: the history of the Request. Any redirect responses will end684 #: up here. The list is sorted from the oldest to the most recent request.685 self.history = []686687 #: Textual reason of responded HTTP Status, e.g. "Not Found" or "OK".688 self.reason = None689690 #: A CookieJar of Cookies the server sent back.691 self.cookies = cookiejar_from_dict({})692693 #: The amount of time elapsed between sending the request694 #: and the arrival of the response (as a timedelta).695 #: This property specifically measures the time taken between sending696 #: the first byte of the request and finishing parsing the headers. It697 #: is therefore unaffected by consuming the response content or the698 #: value of the ``stream`` keyword argument.699 self.elapsed = datetime.timedelta(0)700701 #: The :class:`PreparedRequest <PreparedRequest>` object to which this702 #: is a response.703 self.request = None704705 def __enter__(self):706 return self707708 def __exit__(self, *args):709 self.close()710711 def __getstate__(self):712 # Consume everything; accessing the content attribute makes713 # sure the content has been fully read.714 if not self._content_consumed:715 self.content716717 return {attr: getattr(self, attr, None) for attr in self.__attrs__}718719 def __setstate__(self, state):720 for name, value in state.items():721 setattr(self, name, value)722723 # pickled objects do not have .raw724 setattr(self, "_content_consumed", True)725 setattr(self, "raw", None)726727 def __repr__(self):728 return f"<Response [{self.status_code}]>"729730 def __bool__(self):731 """Returns True if :attr:`status_code` is less than 400.732733 This attribute checks if the status code of the response is between734 400 and 600 to see if there was a client error or a server error. If735 the status code, is between 200 and 400, this will return True. This736 is **not** a check to see if the response code is ``200 OK``.737 """738 return self.ok739740 def __nonzero__(self):741 """Returns True if :attr:`status_code` is less than 400.742743 This attribute checks if the status code of the response is between744 400 and 600 to see if there was a client error or a server error. If745 the status code, is between 200 and 400, this will return True. This746 is **not** a check to see if the response code is ``200 OK``.747 """748 return self.ok749750 def __iter__(self):751 """Allows you to use a response as an iterator."""752 return self.iter_content(128)753754 @property755 def ok(self):756 """Returns True if :attr:`status_code` is less than 400, False if not.757758 This attribute checks if the status code of the response is between759 400 and 600 to see if there was a client error or a server error. If760 the status code is between 200 and 400, this will return True. This761 is **not** a check to see if the response code is ``200 OK``.762 """763 try:764 self.raise_for_status()765 except HTTPError:766 return False767 return True768769 @property770 def is_redirect(self):771 """True if this Response is a well-formed HTTP redirect that could have772 been processed automatically (by :meth:`Session.resolve_redirects`).773 """774 return "location" in self.headers and self.status_code in REDIRECT_STATI775776 @property777 def is_permanent_redirect(self):778 """True if this Response one of the permanent versions of redirect."""779 return "location" in self.headers and self.status_code in (780 codes.moved_permanently,781 codes.permanent_redirect,782 )783784 @property785 def next(self):786 """Returns a PreparedRequest for the next request in a redirect chain, if there is one."""787 return self._next788789 @property790 def apparent_encoding(self):791 """The apparent encoding, provided by the charset_normalizer or chardet libraries."""792 return chardet.detect(self.content)["encoding"]793794 def iter_content(self, chunk_size=1, decode_unicode=False):795 """Iterates over the response data. When stream=True is set on the796 request, this avoids reading the content at once into memory for797 large responses. The chunk size is the number of bytes it should798 read into memory. This is not necessarily the length of each item799 returned as decoding can take place.800801 chunk_size must be of type int or None. A value of None will802 function differently depending on the value of `stream`.803 stream=True will read data as it arrives in whatever size the804 chunks are received. If stream=False, data is returned as805 a single chunk.806807 If decode_unicode is True, content will be decoded using the best808 available encoding based on the response.809 """810811 def generate():812 # Special case for urllib3.813 if hasattr(self.raw, "stream"):814 try:815 yield from self.raw.stream(chunk_size, decode_content=True)816 except ProtocolError as e:817 raise ChunkedEncodingError(e)818 except DecodeError as e:819 raise ContentDecodingError(e)820 except ReadTimeoutError as e:821 raise ConnectionError(e)822 except SSLError as e:823 raise RequestsSSLError(e)824 else:825 # Standard file-like object.826 while True:827 chunk = self.raw.read(chunk_size)828 if not chunk:829 break830 yield chunk831832 self._content_consumed = True833834 if self._content_consumed and isinstance(self._content, bool):835 raise StreamConsumedError()836 elif chunk_size is not None and not isinstance(chunk_size, int):837 raise TypeError(838 f"chunk_size must be an int, it is instead a {type(chunk_size)}."839 )840 # simulate reading small chunks of the content841 reused_chunks = iter_slices(self._content, chunk_size)842843 stream_chunks = generate()844845 chunks = reused_chunks if self._content_consumed else stream_chunks846847 if decode_unicode:848 chunks = stream_decode_response_unicode(chunks, self)849850 return chunks851852 def iter_lines(853 self, chunk_size=ITER_CHUNK_SIZE, decode_unicode=False, delimiter=None854 ):855 """Iterates over the response data, one line at a time. When856 stream=True is set on the request, this avoids reading the857 content at once into memory for large responses.858859 .. note:: This method is not reentrant safe.860 """861862 pending = None863864 for chunk in self.iter_content(865 chunk_size=chunk_size, decode_unicode=decode_unicode866 ):867 if pending is not None:868 chunk = pending + chunk869870 if delimiter:871 lines = chunk.split(delimiter)872 else:873 lines = chunk.splitlines()874875 if lines and lines[-1] and chunk and lines[-1][-1] == chunk[-1]:876 pending = lines.pop()877 else:878 pending = None879880 yield from lines881882 if pending is not None:883 yield pending884885 @property886 def content(self):887 """Content of the response, in bytes."""888889 if self._content is False:890 # Read the contents.891 if self._content_consumed:892 raise RuntimeError("The content for this response was already consumed")893894 if self.status_code == 0 or self.raw is None:895 self._content = None896 else:897 self._content = b"".join(self.iter_content(CONTENT_CHUNK_SIZE)) or b""898899 self._content_consumed = True900 # don't need to release the connection; that's been handled by urllib3901 # since we exhausted the data.902 return self._content903904 @property905 def text(self):906 """Content of the response, in unicode.907908 If Response.encoding is None, encoding will be guessed using909 ``charset_normalizer`` or ``chardet``.910911 The encoding of the response content is determined based solely on HTTP912 headers, following RFC 2616 to the letter. If you can take advantage of913 non-HTTP knowledge to make a better guess at the encoding, you should914 set ``r.encoding`` appropriately before accessing this property.915 """916917 # Try charset from content-type918 content = None919 encoding = self.encoding920921 if not self.content:922 return ""923924 # Fallback to auto-detected encoding.925 if self.encoding is None:926 encoding = self.apparent_encoding927928 # Decode unicode from given encoding.929 try:930 content = str(self.content, encoding, errors="replace")931 except (LookupError, TypeError):932 # A LookupError is raised if the encoding was not found which could933 # indicate a misspelling or similar mistake.934 #935 # A TypeError can be raised if encoding is None936 #937 # So we try blindly encoding.938 content = str(self.content, errors="replace")939940 return content941942 def json(self, **kwargs):943 r"""Returns the json-encoded content of a response, if any.944945 :param \*\*kwargs: Optional arguments that ``json.loads`` takes.946 :raises requests.exceptions.JSONDecodeError: If the response body does not947 contain valid json.948 """949950 if not self.encoding and self.content and len(self.content) > 3:951 # No encoding set. JSON RFC 4627 section 3 states we should expect952 # UTF-8, -16 or -32. Detect which one to use; If the detection or953 # decoding fails, fall back to `self.text` (using charset_normalizer to make954 # a best guess).955 encoding = guess_json_utf(self.content)956 if encoding is not None:957 try:958 return complexjson.loads(self.content.decode(encoding), **kwargs)959 except UnicodeDecodeError:960 # Wrong UTF codec detected; usually because it's not UTF-8961 # but some other 8-bit codec. This is an RFC violation,962 # and the server didn't bother to tell us what codec *was*963 # used.964 pass965 except JSONDecodeError as e:966 raise RequestsJSONDecodeError(e.msg, e.doc, e.pos)967968 try:969 return complexjson.loads(self.text, **kwargs)970 except JSONDecodeError as e:971 # Catch JSON-related errors and raise as requests.JSONDecodeError972 # This aliases json.JSONDecodeError and simplejson.JSONDecodeError973 raise RequestsJSONDecodeError(e.msg, e.doc, e.pos)974975 @property976 def links(self):977 """Returns the parsed header links of the response, if any."""978979 header = self.headers.get("link")980981 resolved_links = {}982983 if header:984 links = parse_header_links(header)985986 for link in links:987 key = link.get("rel") or link.get("url")988 resolved_links[key] = link989990 return resolved_links991992 def raise_for_status(self):993 """Raises :class:`HTTPError`, if one occurred."""994995 http_error_msg = ""996 if isinstance(self.reason, bytes):997 # We attempt to decode utf-8 first because some servers998 # choose to localize their reason strings. If the string999 # isn't utf-8, we fall back to iso-8859-1 for all other1000 # encodings. (See PR #3538)1001 try:1002 reason = self.reason.decode("utf-8")1003 except UnicodeDecodeError:1004 reason = self.reason.decode("iso-8859-1")1005 else:1006 reason = self.reason10071008 if 400 <= self.status_code < 500:1009 http_error_msg = (1010 f"{self.status_code} Client Error: {reason} for url: {self.url}"1011 )10121013 elif 500 <= self.status_code < 600:1014 http_error_msg = (1015 f"{self.status_code} Server Error: {reason} for url: {self.url}"1016 )10171018 if http_error_msg:1019 raise HTTPError(http_error_msg, response=self)10201021 def close(self):1022 """Releases the connection back to the pool. Once this method has been1023 called the underlying ``raw`` object must not be accessed again.10241025 *Note: Should not normally need to be called explicitly.*1026 """1027 if not self._content_consumed:1028 self.raw.close()10291030 release_conn = getattr(self.raw, "release_conn", None)1031 if release_conn is not None:1032 release_conn()
deleted:requests/packages.py-28 removed
1import sys23try:4 import chardet5except ImportError:6 import warnings78 import charset_normalizer as chardet910 warnings.filterwarnings("ignore", "Trying to detect", module="charset_normalizer")1112# This code exists for backwards compatibility reasons.13# I don't like it either. Just look the other way. :)1415for package in ("urllib3", "idna"):16 locals()[package] = __import__(package)17 # This traversal is apparently necessary such that the identities are18 # preserved (requests.packages.urllib3.* is urllib3.*)19 for mod in list(sys.modules):20 if mod == package or mod.startswith(f"{package}."):21 sys.modules[f"requests.packages.{mod}"] = sys.modules[mod]2223target = chardet.__name__24for mod in list(sys.modules):25 if mod == target or mod.startswith(f"{target}."):26 target = target.replace(target, "chardet")27 sys.modules[f"requests.packages.{target}"] = sys.modules[mod]28# Kinda cool, though, right?
deleted:requests/sessions.py-831 removed
1"""2requests.sessions3~~~~~~~~~~~~~~~~~45This module provides a Session object to manage and persist settings across6requests (cookies, auth, proxies).7"""8import os9import sys10import time11from collections import OrderedDict12from datetime import timedelta1314from ._internal_utils import to_native_string15from .adapters import HTTPAdapter16from .auth import _basic_auth_str17from .compat import Mapping, cookielib, urljoin, urlparse18from .cookies import (19 RequestsCookieJar,20 cookiejar_from_dict,21 extract_cookies_to_jar,22 merge_cookies,23)24from .exceptions import (25 ChunkedEncodingError,26 ContentDecodingError,27 InvalidSchema,28 TooManyRedirects,29)30from .hooks import default_hooks, dispatch_hook3132# formerly defined here, reexposed here for backward compatibility33from .models import ( # noqa: F40134 DEFAULT_REDIRECT_LIMIT,35 REDIRECT_STATI,36 PreparedRequest,37 Request,38)39from .status_codes import codes40from .structures import CaseInsensitiveDict41from .utils import ( # noqa: F40142 DEFAULT_PORTS,43 default_headers,44 get_auth_from_url,45 get_environ_proxies,46 get_netrc_auth,47 requote_uri,48 resolve_proxies,49 rewind_body,50 should_bypass_proxies,51 to_key_val_list,52)5354# Preferred clock, based on which one is more accurate on a given system.55if sys.platform == "win32":56 preferred_clock = time.perf_counter57else:58 preferred_clock = time.time596061def merge_setting(request_setting, session_setting, dict_class=OrderedDict):62 """Determines appropriate setting for a given request, taking into account63 the explicit setting on that request, and the setting in the session. If a64 setting is a dictionary, they will be merged together using `dict_class`65 """6667 if session_setting is None:68 return request_setting6970 if request_setting is None:71 return session_setting7273 # Bypass if not a dictionary (e.g. verify)74 if not (75 isinstance(session_setting, Mapping) and isinstance(request_setting, Mapping)76 ):77 return request_setting7879 merged_setting = dict_class(to_key_val_list(session_setting))80 merged_setting.update(to_key_val_list(request_setting))8182 # Remove keys that are set to None. Extract keys first to avoid altering83 # the dictionary during iteration.84 none_keys = [k for (k, v) in merged_setting.items() if v is None]85 for key in none_keys:86 del merged_setting[key]8788 return merged_setting899091def merge_hooks(request_hooks, session_hooks, dict_class=OrderedDict):92 """Properly merges both requests and session hooks.9394 This is necessary because when request_hooks == {'response': []}, the95 merge breaks Session hooks entirely.96 """97 if session_hooks is None or session_hooks.get("response") == []:98 return request_hooks99100 if request_hooks is None or request_hooks.get("response") == []:101 return session_hooks102103 return merge_setting(request_hooks, session_hooks, dict_class)104105106class SessionRedirectMixin:107 def get_redirect_target(self, resp):108 """Receives a Response. Returns a redirect URI or ``None``"""109 # Due to the nature of how requests processes redirects this method will110 # be called at least once upon the original response and at least twice111 # on each subsequent redirect response (if any).112 # If a custom mixin is used to handle this logic, it may be advantageous113 # to cache the redirect location onto the response object as a private114 # attribute.115 if resp.is_redirect:116 location = resp.headers["location"]117 # Currently the underlying http module on py3 decode headers118 # in latin1, but empirical evidence suggests that latin1 is very119 # rarely used with non-ASCII characters in HTTP headers.120 # It is more likely to get UTF8 header rather than latin1.121 # This causes incorrect handling of UTF8 encoded location headers.122 # To solve this, we re-encode the location in latin1.123 location = location.encode("latin1")124 return to_native_string(location, "utf8")125 return None126127 def should_strip_auth(self, old_url, new_url):128 """Decide whether Authorization header should be removed when redirecting"""129 old_parsed = urlparse(old_url)130 new_parsed = urlparse(new_url)131 if old_parsed.hostname != new_parsed.hostname:132 return True133 # Special case: allow http -> https redirect when using the standard134 # ports. This isn't specified by RFC 7235, but is kept to avoid135 # breaking backwards compatibility with older versions of requests136 # that allowed any redirects on the same host.137 if (138 old_parsed.scheme == "http"139 and old_parsed.port in (80, None)140 and new_parsed.scheme == "https"141 and new_parsed.port in (443, None)142 ):143 return False144145 # Handle default port usage corresponding to scheme.146 changed_port = old_parsed.port != new_parsed.port147 changed_scheme = old_parsed.scheme != new_parsed.scheme148 default_port = (DEFAULT_PORTS.get(old_parsed.scheme, None), None)149 if (150 not changed_scheme151 and old_parsed.port in default_port152 and new_parsed.port in default_port153 ):154 return False155156 # Standard case: root URI must match157 return changed_port or changed_scheme158159 def resolve_redirects(160 self,161 resp,162 req,163 stream=False,164 timeout=None,165 verify=True,166 cert=None,167 proxies=None,168 yield_requests=False,169 **adapter_kwargs,170 ):171 """Receives a Response. Returns a generator of Responses or Requests."""172173 hist = [] # keep track of history174175 url = self.get_redirect_target(resp)176 previous_fragment = urlparse(req.url).fragment177 while url:178 prepared_request = req.copy()179180 # Update history and keep track of redirects.181 # resp.history must ignore the original request in this loop182 hist.append(resp)183 resp.history = hist[1:]184185 try:186 resp.content # Consume socket so it can be released187 except (ChunkedEncodingError, ContentDecodingError, RuntimeError):188 resp.raw.read(decode_content=False)189190 if len(resp.history) >= self.max_redirects:191 raise TooManyRedirects(192 f"Exceeded {self.max_redirects} redirects.", response=resp193 )194195 # Release the connection back into the pool.196 resp.close()197198 # Handle redirection without scheme (see: RFC 1808 Section 4)199 if url.startswith("//"):200 parsed_rurl = urlparse(resp.url)201 url = ":".join([to_native_string(parsed_rurl.scheme), url])202203 # Normalize url case and attach previous fragment if needed (RFC 7231 7.1.2)204 parsed = urlparse(url)205 if parsed.fragment == "" and previous_fragment:206 parsed = parsed._replace(fragment=previous_fragment)207 elif parsed.fragment:208 previous_fragment = parsed.fragment209 url = parsed.geturl()210211 # Facilitate relative 'location' headers, as allowed by RFC 7231.212 # (e.g. '/path/to/resource' instead of 'http://domain.tld/path/to/resource')213 # Compliant with RFC3986, we percent encode the url.214 if not parsed.netloc:215 url = urljoin(resp.url, requote_uri(url))216 else:217 url = requote_uri(url)218219 prepared_request.url = to_native_string(url)220221 self.rebuild_method(prepared_request, resp)222223 # https://github.com/psf/requests/issues/1084224 if resp.status_code not in (225 codes.temporary_redirect,226 codes.permanent_redirect,227 ):228 # https://github.com/psf/requests/issues/3490229 purged_headers = ("Content-Length", "Content-Type", "Transfer-Encoding")230 for header in purged_headers:231 prepared_request.headers.pop(header, None)232 prepared_request.body = None233234 headers = prepared_request.headers235 headers.pop("Cookie", None)236237 # Extract any cookies sent on the response to the cookiejar238 # in the new request. Because we've mutated our copied prepared239 # request, use the old one that we haven't yet touched.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)243244 # Rebuild auth and proxy information.245 proxies = self.rebuild_proxies(prepared_request, proxies)246 self.rebuild_auth(prepared_request, resp)247248 # A failed tell() sets `_body_position` to `object()`. This non-None249 # value ensures `rewindable` will be True, allowing us to raise an250 # UnrewindableBodyError, instead of hanging the connection.251 rewindable = prepared_request._body_position is not None and (252 "Content-Length" in headers or "Transfer-Encoding" in headers253 )254255 # Attempt to rewind consumed file-like object.256 if rewindable:257 rewind_body(prepared_request)258259 # Override the original request.260 req = prepared_request261262 if yield_requests:263 yield req264 else:265 resp = self.send(266 req,267 stream=stream,268 timeout=timeout,269 verify=verify,270 cert=cert,271 proxies=proxies,272 allow_redirects=False,273 **adapter_kwargs,274 )275276 extract_cookies_to_jar(self.cookies, prepared_request, resp.raw)277278 # extract redirect url, if any, for the next loop279 url = self.get_redirect_target(resp)280 yield resp281282 def rebuild_auth(self, prepared_request, response):283 """When being redirected we may want to strip authentication from the284 request to avoid leaking credentials. This method intelligently removes285 and reapplies authentication where possible to avoid credential loss.286 """287 headers = prepared_request.headers288 url = prepared_request.url289290 if "Authorization" in headers and self.should_strip_auth(291 response.request.url, url292 ):293 # If we get redirected to a new host, we should strip out any294 # authentication headers.295 del headers["Authorization"]296297 # .netrc might have more auth for us on our new host.298 new_auth = get_netrc_auth(url) if self.trust_env else None299 if new_auth is not None:300 prepared_request.prepare_auth(new_auth)301302 def rebuild_proxies(self, prepared_request, proxies):303 """This method re-evaluates the proxy configuration by considering the304 environment variables. If we are redirected to a URL covered by305 NO_PROXY, we strip the proxy configuration. Otherwise, we set missing306 proxy keys for this URL (in case they were stripped by a previous307 redirect).308309 This method also replaces the Proxy-Authorization header where310 necessary.311312 :rtype: dict313 """314 headers = prepared_request.headers315 scheme = urlparse(prepared_request.url).scheme316 new_proxies = resolve_proxies(prepared_request, proxies, self.trust_env)317318 if "Proxy-Authorization" in headers:319 del headers["Proxy-Authorization"]320321 try:322 username, password = get_auth_from_url(new_proxies[scheme])323 except KeyError:324 username, password = None, None325326 # urllib3 handles proxy authorization for us in the standard adapter.327 # Avoid appending this to TLS tunneled requests where it may be leaked.328 if not scheme.startswith("https") and username and password:329 headers["Proxy-Authorization"] = _basic_auth_str(username, password)330331 return new_proxies332333 def rebuild_method(self, prepared_request, response):334 """When being redirected we may want to change the method of the request335 based on certain specs or browser behavior.336 """337 method = prepared_request.method338339 # https://tools.ietf.org/html/rfc7231#section-6.4.4340 if response.status_code == codes.see_other and method != "HEAD":341 method = "GET"342343 # Do what the browsers do, despite standards...344 # First, turn 302s into GETs.345 if response.status_code == codes.found and method != "HEAD":346 method = "GET"347348 # Second, if a POST is responded to with a 301, turn it into a GET.349 # This bizarre behaviour is explained in Issue 1704.350 if response.status_code == codes.moved and method == "POST":351 method = "GET"352353 prepared_request.method = method354355356class Session(SessionRedirectMixin):357 """A Requests session.358359 Provides cookie persistence, connection-pooling, and configuration.360361 Basic Usage::362363 >>> import requests364 >>> s = requests.Session()365 >>> s.get('https://httpbin.org/get')366 <Response [200]>367368 Or as a context manager::369370 >>> with requests.Session() as s:371 ... s.get('https://httpbin.org/get')372 <Response [200]>373 """374375 __attrs__ = [376 "headers",377 "cookies",378 "auth",379 "proxies",380 "hooks",381 "params",382 "verify",383 "cert",384 "adapters",385 "stream",386 "trust_env",387 "max_redirects",388 ]389390 def __init__(self):391 #: A case-insensitive dictionary of headers to be sent on each392 #: :class:`Request <Request>` sent from this393 #: :class:`Session <Session>`.394 self.headers = default_headers()395396 #: Default Authentication tuple or object to attach to397 #: :class:`Request <Request>`.398 self.auth = None399400 #: Dictionary mapping protocol or protocol and host to the URL of the proxy401 #: (e.g. {'http': 'foo.bar:3128', 'http://host.name': 'foo.bar:4012'}) to402 #: be used on each :class:`Request <Request>`.403 self.proxies = {}404405 #: Event-handling hooks.406 self.hooks = default_hooks()407408 #: Dictionary of querystring data to attach to each409 #: :class:`Request <Request>`. The dictionary values may be lists for410 #: representing multivalued query parameters.411 self.params = {}412413 #: Stream response content default.414 self.stream = False415416 #: SSL Verification default.417 #: Defaults to `True`, requiring requests to verify the TLS certificate at the418 #: remote end.419 #: If verify is set to `False`, requests will accept any TLS certificate420 #: presented by the server, and will ignore hostname mismatches and/or421 #: expired certificates, which will make your application vulnerable to422 #: man-in-the-middle (MitM) attacks.423 #: Only set this to `False` for testing.424 self.verify = True425426 #: SSL client certificate default, if String, path to ssl client427 #: cert file (.pem). If Tuple, ('cert', 'key') pair.428 self.cert = None429430 #: Maximum number of redirects allowed. If the request exceeds this431 #: limit, a :class:`TooManyRedirects` exception is raised.432 #: This defaults to requests.models.DEFAULT_REDIRECT_LIMIT, which is433 #: 30.434 self.max_redirects = DEFAULT_REDIRECT_LIMIT435436 #: Trust environment settings for proxy configuration, default437 #: authentication and similar.438 self.trust_env = True439440 #: A CookieJar containing all currently outstanding cookies set on this441 #: session. By default it is a442 #: :class:`RequestsCookieJar <requests.cookies.RequestsCookieJar>`, but443 #: may be any other ``cookielib.CookieJar`` compatible object.444 self.cookies = cookiejar_from_dict({})445446 # Default connection adapters.447 self.adapters = OrderedDict()448 self.mount("https://", HTTPAdapter())449 self.mount("http://", HTTPAdapter())450451 def __enter__(self):452 return self453454 def __exit__(self, *args):455 self.close()456457 def prepare_request(self, request):458 """Constructs a :class:`PreparedRequest <PreparedRequest>` for459 transmission and returns it. The :class:`PreparedRequest` has settings460 merged from the :class:`Request <Request>` instance and those of the461 :class:`Session`.462463 :param request: :class:`Request` instance to prepare with this464 session's settings.465 :rtype: requests.PreparedRequest466 """467 cookies = request.cookies or {}468469 # Bootstrap CookieJar.470 if not isinstance(cookies, cookielib.CookieJar):471 cookies = cookiejar_from_dict(cookies)472473 # Merge with session cookies474 merged_cookies = merge_cookies(475 merge_cookies(RequestsCookieJar(), self.cookies), cookies476 )477478 # Set environment's basic authentication if not explicitly set.479 auth = request.auth480 if self.trust_env and not auth and not self.auth:481 auth = get_netrc_auth(request.url)482483 p = PreparedRequest()484 p.prepare(485 method=request.method.upper(),486 url=request.url,487 files=request.files,488 data=request.data,489 json=request.json,490 headers=merge_setting(491 request.headers, self.headers, dict_class=CaseInsensitiveDict492 ),493 params=merge_setting(request.params, self.params),494 auth=merge_setting(auth, self.auth),495 cookies=merged_cookies,496 hooks=merge_hooks(request.hooks, self.hooks),497 )498 return p499500 def request(501 self,502 method,503 url,504 params=None,505 data=None,506 headers=None,507 cookies=None,508 files=None,509 auth=None,510 timeout=None,511 allow_redirects=True,512 proxies=None,513 hooks=None,514 stream=None,515 verify=None,516 cert=None,517 json=None,518 ):519 """Constructs a :class:`Request <Request>`, prepares it and sends it.520 Returns :class:`Response <Response>` object.521522 :param method: method for the new :class:`Request` object.523 :param url: URL for the new :class:`Request` object.524 :param params: (optional) Dictionary or bytes to be sent in the query525 string for the :class:`Request`.526 :param data: (optional) Dictionary, list of tuples, bytes, or file-like527 object to send in the body of the :class:`Request`.528 :param json: (optional) json to send in the body of the529 :class:`Request`.530 :param headers: (optional) Dictionary of HTTP Headers to send with the531 :class:`Request`.532 :param cookies: (optional) Dict or CookieJar object to send with the533 :class:`Request`.534 :param files: (optional) Dictionary of ``'filename': file-like-objects``535 for multipart encoding upload.536 :param auth: (optional) Auth tuple or callable to enable537 Basic/Digest/Custom HTTP Auth.538 :param timeout: (optional) How long to wait for the server to send539 data before giving up, as a float, or a :ref:`(connect timeout,540 read timeout) <timeouts>` tuple.541 :type timeout: float or tuple542 :param allow_redirects: (optional) Set to True by default.543 :type allow_redirects: bool544 :param proxies: (optional) Dictionary mapping protocol or protocol and545 hostname to the URL of the proxy.546 :param hooks: (optional) Dictionary mapping hook name to one event or547 list of events, event must be callable.548 :param stream: (optional) whether to immediately download the response549 content. Defaults to ``False``.550 :param verify: (optional) Either a boolean, in which case it controls whether we verify551 the server's TLS certificate, or a string, in which case it must be a path552 to a CA bundle to use. Defaults to ``True``. When set to553 ``False``, requests will accept any TLS certificate presented by554 the server, and will ignore hostname mismatches and/or expired555 certificates, which will make your application vulnerable to556 man-in-the-middle (MitM) attacks. Setting verify to ``False``557 may be useful during local development or testing.558 :param cert: (optional) if String, path to ssl client cert file (.pem).559 If Tuple, ('cert', 'key') pair.560 :rtype: requests.Response561 """562 # Create the Request.563 req = Request(564 method=method.upper(),565 url=url,566 headers=headers,567 files=files,568 data=data or {},569 json=json,570 params=params or {},571 auth=auth,572 cookies=cookies,573 hooks=hooks,574 )575 prep = self.prepare_request(req)576577 proxies = proxies or {}578579 settings = self.merge_environment_settings(580 prep.url, proxies, stream, verify, cert581 )582583 # Send the request.584 send_kwargs = {585 "timeout": timeout,586 "allow_redirects": allow_redirects,587 }588 send_kwargs.update(settings)589 resp = self.send(prep, **send_kwargs)590591 return resp592593 def get(self, url, **kwargs):594 r"""Sends a GET request. Returns :class:`Response` object.595596 :param url: URL for the new :class:`Request` object.597 :param \*\*kwargs: Optional arguments that ``request`` takes.598 :rtype: requests.Response599 """600601 kwargs.setdefault("allow_redirects", True)602 return self.request("GET", url, **kwargs)603604 def options(self, url, **kwargs):605 r"""Sends a OPTIONS request. Returns :class:`Response` object.606607 :param url: URL for the new :class:`Request` object.608 :param \*\*kwargs: Optional arguments that ``request`` takes.609 :rtype: requests.Response610 """611612 kwargs.setdefault("allow_redirects", True)613 return self.request("OPTIONS", url, **kwargs)614615 def head(self, url, **kwargs):616 r"""Sends a HEAD request. Returns :class:`Response` object.617618 :param url: URL for the new :class:`Request` object.619 :param \*\*kwargs: Optional arguments that ``request`` takes.620 :rtype: requests.Response621 """622623 kwargs.setdefault("allow_redirects", False)624 return self.request("HEAD", url, **kwargs)625626 def post(self, url, data=None, json=None, **kwargs):627 r"""Sends a POST request. Returns :class:`Response` object.628629 :param url: URL for the new :class:`Request` object.630 :param data: (optional) Dictionary, list of tuples, bytes, or file-like631 object to send in the body of the :class:`Request`.632 :param json: (optional) json to send in the body of the :class:`Request`.633 :param \*\*kwargs: Optional arguments that ``request`` takes.634 :rtype: requests.Response635 """636637 return self.request("POST", url, data=data, json=json, **kwargs)638639 def put(self, url, data=None, **kwargs):640 r"""Sends a PUT request. Returns :class:`Response` object.641642 :param url: URL for the new :class:`Request` object.643 :param data: (optional) Dictionary, list of tuples, bytes, or file-like644 object to send in the body of the :class:`Request`.645 :param \*\*kwargs: Optional arguments that ``request`` takes.646 :rtype: requests.Response647 """648649 return self.request("PUT", url, data=data, **kwargs)650651 def patch(self, url, data=None, **kwargs):652 r"""Sends a PATCH request. Returns :class:`Response` object.653654 :param url: URL for the new :class:`Request` object.655 :param data: (optional) Dictionary, list of tuples, bytes, or file-like656 object to send in the body of the :class:`Request`.657 :param \*\*kwargs: Optional arguments that ``request`` takes.658 :rtype: requests.Response659 """660661 return self.request("PATCH", url, data=data, **kwargs)662663 def delete(self, url, **kwargs):664 r"""Sends a DELETE request. Returns :class:`Response` object.665666 :param url: URL for the new :class:`Request` object.667 :param \*\*kwargs: Optional arguments that ``request`` takes.668 :rtype: requests.Response669 """670671 return self.request("DELETE", url, **kwargs)672673 def send(self, request, **kwargs):674 """Send a given PreparedRequest.675676 :rtype: requests.Response677 """678 # Set defaults that the hooks can utilize to ensure they always have679 # the correct parameters to reproduce the previous request.680 kwargs.setdefault("stream", self.stream)681 kwargs.setdefault("verify", self.verify)682 kwargs.setdefault("cert", self.cert)683 if "proxies" not in kwargs:684 kwargs["proxies"] = resolve_proxies(request, self.proxies, self.trust_env)685686 # It's possible that users might accidentally send a Request object.687 # Guard against that specific failure case.688 if isinstance(request, Request):689 raise ValueError("You can only send PreparedRequests.")690691 # Set up variables needed for resolve_redirects and dispatching of hooks692 allow_redirects = kwargs.pop("allow_redirects", True)693 stream = kwargs.get("stream")694 hooks = request.hooks695696 # Get the appropriate adapter to use697 adapter = self.get_adapter(url=request.url)698699 # Start time (approximately) of the request700 start = preferred_clock()701702 # Send the request703 r = adapter.send(request, **kwargs)704705 # Total elapsed time of the request (approximately)706 elapsed = preferred_clock() - start707 r.elapsed = timedelta(seconds=elapsed)708709 # Response manipulation hooks710 r = dispatch_hook("response", hooks, r, **kwargs)711712 # Persist cookies713 if r.history:714 # If the hooks create history then we want those cookies too715 for resp in r.history:716 extract_cookies_to_jar(self.cookies, resp.request, resp.raw)717718 extract_cookies_to_jar(self.cookies, request, r.raw)719720 # Resolve redirects if allowed.721 if allow_redirects:722 # Redirect resolving generator.723 gen = self.resolve_redirects(r, request, **kwargs)724 history = [resp for resp in gen]725 else:726 history = []727728 # Shuffle things around if there's history.729 if history:730 # Insert the first (original) request at the start731 history.insert(0, r)732 # Get the last request made733 r = history.pop()734 r.history = history735736 # If redirects aren't being followed, store the response on the Request for Response.next().737 if not allow_redirects:738 try:739 r._next = next(740 self.resolve_redirects(r, request, yield_requests=True, **kwargs)741 )742 except StopIteration:743 pass744745 if not stream:746 r.content747748 return r749750 def merge_environment_settings(self, url, proxies, stream, verify, cert):751 """752 Check the environment and merge it with some settings.753754 :rtype: dict755 """756 # Gather clues from the surrounding environment.757 if self.trust_env:758 # Set environment's proxies.759 no_proxy = proxies.get("no_proxy") if proxies is not None else None760 env_proxies = get_environ_proxies(url, no_proxy=no_proxy)761 for k, v in env_proxies.items():762 proxies.setdefault(k, v)763764 # Look for requests environment configuration765 # and be compatible with cURL.766 if verify is True or verify is None:767 verify = (768 os.environ.get("REQUESTS_CA_BUNDLE")769 or os.environ.get("CURL_CA_BUNDLE")770 or verify771 )772773 # Merge all the kwargs.774 proxies = merge_setting(proxies, self.proxies)775 stream = merge_setting(stream, self.stream)776 verify = merge_setting(verify, self.verify)777 cert = merge_setting(cert, self.cert)778779 return {"proxies": proxies, "stream": stream, "verify": verify, "cert": cert}780781 def get_adapter(self, url):782 """783 Returns the appropriate connection adapter for the given URL.784785 :rtype: requests.adapters.BaseAdapter786 """787 for prefix, adapter in self.adapters.items():788 if url.lower().startswith(prefix.lower()):789 return adapter790791 # Nothing matches :-/792 raise InvalidSchema(f"No connection adapters were found for {url!r}")793794 def close(self):795 """Closes all adapters and as such the session"""796 for v in self.adapters.values():797 v.close()798799 def mount(self, prefix, adapter):800 """Registers a connection adapter to a prefix.801802 Adapters are sorted in descending order by prefix length.803 """804 self.adapters[prefix] = adapter805 keys_to_move = [k for k in self.adapters if len(k) < len(prefix)]806807 for key in keys_to_move:808 self.adapters[key] = self.adapters.pop(key)809810 def __getstate__(self):811 state = {attr: getattr(self, attr, None) for attr in self.__attrs__}812 return state813814 def __setstate__(self, state):815 for attr, value in state.items():816 setattr(self, attr, value)817818819def session():820 """821 Returns a :class:`Session` for context-management.822823 .. deprecated:: 1.0.0824825 This method has been deprecated since version 1.0.0 and is only kept for826 backwards compatibility. New code should use :class:`~requests.sessions.Session`827 to create a session. This may be removed at a future date.828829 :rtype: Session830 """831 return Session()
deleted:requests/status_codes.py-128 removed
1r"""2The ``codes`` object defines a mapping from common names for HTTP statuses3to their numerical codes, accessible either as attributes or as dictionary4items.56Example::78 >>> import requests9 >>> requests.codes['temporary_redirect']10 30711 >>> requests.codes.teapot12 41813 >>> requests.codes['\o/']14 2001516Some codes have multiple names, and both upper- and lower-case versions of17the names are allowed. For example, ``codes.ok``, ``codes.OK``, and18``codes.okay`` all correspond to the HTTP status code 200.19"""2021from .structures import LookupDict2223_codes = {24 # Informational.25 100: ("continue",),26 101: ("switching_protocols",),27 102: ("processing",),28 103: ("checkpoint",),29 122: ("uri_too_long", "request_uri_too_long"),30 200: ("ok", "okay", "all_ok", "all_okay", "all_good", "\\o/", "✓"),31 201: ("created",),32 202: ("accepted",),33 203: ("non_authoritative_info", "non_authoritative_information"),34 204: ("no_content",),35 205: ("reset_content", "reset"),36 206: ("partial_content", "partial"),37 207: ("multi_status", "multiple_status", "multi_stati", "multiple_stati"),38 208: ("already_reported",),39 226: ("im_used",),40 # Redirection.41 300: ("multiple_choices",),42 301: ("moved_permanently", "moved", "\\o-"),43 302: ("found",),44 303: ("see_other", "other"),45 304: ("not_modified",),46 305: ("use_proxy",),47 306: ("switch_proxy",),48 307: ("temporary_redirect", "temporary_moved", "temporary"),49 308: (50 "permanent_redirect",51 "resume_incomplete",52 "resume",53 ), # "resume" and "resume_incomplete" to be removed in 3.054 # Client Error.55 400: ("bad_request", "bad"),56 401: ("unauthorized",),57 402: ("payment_required", "payment"),58 403: ("forbidden",),59 404: ("not_found", "-o-"),60 405: ("method_not_allowed", "not_allowed"),61 406: ("not_acceptable",),62 407: ("proxy_authentication_required", "proxy_auth", "proxy_authentication"),63 408: ("request_timeout", "timeout"),64 409: ("conflict",),65 410: ("gone",),66 411: ("length_required",),67 412: ("precondition_failed", "precondition"),68 413: ("request_entity_too_large",),69 414: ("request_uri_too_large",),70 415: ("unsupported_media_type", "unsupported_media", "media_type"),71 416: (72 "requested_range_not_satisfiable",73 "requested_range",74 "range_not_satisfiable",75 ),76 417: ("expectation_failed",),77 418: ("im_a_teapot", "teapot", "i_am_a_teapot"),78 421: ("misdirected_request",),79 422: ("unprocessable_entity", "unprocessable"),80 423: ("locked",),81 424: ("failed_dependency", "dependency"),82 425: ("unordered_collection", "unordered"),83 426: ("upgrade_required", "upgrade"),84 428: ("precondition_required", "precondition"),85 429: ("too_many_requests", "too_many"),86 431: ("header_fields_too_large", "fields_too_large"),87 444: ("no_response", "none"),88 449: ("retry_with", "retry"),89 450: ("blocked_by_windows_parental_controls", "parental_controls"),90 451: ("unavailable_for_legal_reasons", "legal_reasons"),91 499: ("client_closed_request",),92 # Server Error.93 500: ("internal_server_error", "server_error", "/o\\", "✗"),94 501: ("not_implemented",),95 502: ("bad_gateway",),96 503: ("service_unavailable", "unavailable"),97 504: ("gateway_timeout",),98 505: ("http_version_not_supported", "http_version"),99 506: ("variant_also_negotiates",),100 507: ("insufficient_storage",),101 509: ("bandwidth_limit_exceeded", "bandwidth"),102 510: ("not_extended",),103 511: ("network_authentication_required", "network_auth", "network_authentication"),104}105106codes = LookupDict(name="status_codes")107108109def _init():110 for code, titles in _codes.items():111 for title in titles:112 setattr(codes, title, code)113 if not title.startswith(("\\", "/")):114 setattr(codes, title.upper(), code)115116 def doc(code):117 names = ", ".join(f"``{n}``" for n in _codes[code])118 return "* %d: %s" % (code, names)119120 global __doc__121 __doc__ = (122 __doc__ + "\n" + "\n".join(doc(code) for code in sorted(_codes))123 if __doc__ is not None124 else None125 )126127128_init()
deleted:requests/structures.py-99 removed
1"""2requests.structures3~~~~~~~~~~~~~~~~~~~45Data structures that power Requests.6"""78from collections import OrderedDict910from .compat import Mapping, MutableMapping111213class CaseInsensitiveDict(MutableMapping):14 """A case-insensitive ``dict``-like object.1516 Implements all methods and operations of17 ``MutableMapping`` as well as dict's ``copy``. Also18 provides ``lower_items``.1920 All keys are expected to be strings. The structure remembers the21 case of the last key to be set, and ``iter(instance)``,22 ``keys()``, ``items()``, ``iterkeys()``, and ``iteritems()``23 will contain case-sensitive keys. However, querying and contains24 testing is case insensitive::2526 cid = CaseInsensitiveDict()27 cid['Accept'] = 'application/json'28 cid['aCCEPT'] == 'application/json' # True29 list(cid) == ['Accept'] # True3031 For example, ``headers['content-encoding']`` will return the32 value of a ``'Content-Encoding'`` response header, regardless33 of how the header name was originally stored.3435 If the constructor, ``.update``, or equality comparison36 operations are given keys that have equal ``.lower()``s, the37 behavior is undefined.38 """3940 def __init__(self, data=None, **kwargs):41 self._store = OrderedDict()42 if data is None:43 data = {}44 self.update(data, **kwargs)4546 def __setitem__(self, key, value):47 # Use the lowercased key for lookups, but store the actual48 # key alongside the value.49 self._store[key.lower()] = (key, value)5051 def __getitem__(self, key):52 return self._store[key.lower()][1]5354 def __delitem__(self, key):55 del self._store[key.lower()]5657 def __iter__(self):58 return (casedkey for casedkey, mappedvalue in self._store.values())5960 def __len__(self):61 return len(self._store)6263 def lower_items(self):64 """Like iteritems(), but with all lowercase keys."""65 return ((lowerkey, keyval[1]) for (lowerkey, keyval) in self._store.items())6667 def __eq__(self, other):68 if isinstance(other, Mapping):69 other = CaseInsensitiveDict(other)70 else:71 return NotImplemented72 # Compare insensitively73 return dict(self.lower_items()) == dict(other.lower_items())7475 # Copy is required76 def copy(self):77 return CaseInsensitiveDict(self._store.values())7879 def __repr__(self):80 return str(dict(self.items()))818283class LookupDict(dict):84 """Dictionary lookup object."""8586 def __init__(self, name=None):87 self.name = name88 super().__init__()8990 def __repr__(self):91 return f"<lookup '{self.name}'>"9293 def __getitem__(self, key):94 # We allow fall-through here, so values default to None9596 return self.__dict__.get(key, None)9798 def get(self, key, default=None):99 return self.__dict__.get(key, default)
deleted:requests/utils.py-1091 removed
1"""2requests.utils3~~~~~~~~~~~~~~45This module provides utility functions that are used within Requests6that are also useful for external consumption.7"""89import codecs10import contextlib11import io12import os13import re14import socket15import struct16import sys17import tempfile18import warnings19import zipfile20from collections import OrderedDict2122from urllib3.util import make_headers, parse_url2324from . import certs25from .__version__ import __version__2627# to_native_string is unused here, but imported here for backwards compatibility28from ._internal_utils import ( # noqa: F40129 _HEADER_VALIDATORS_BYTE,30 _HEADER_VALIDATORS_STR,31 HEADER_VALIDATORS,32 to_native_string,33)34from .compat import (35 Mapping,36 basestring,37 bytes,38 getproxies,39 getproxies_environment,40 integer_types,41)42from .compat import parse_http_list as _parse_list_header43from .compat import (44 proxy_bypass,45 proxy_bypass_environment,46 quote,47 str,48 unquote,49 urlparse,50 urlunparse,51)52from .cookies import cookiejar_from_dict53from .exceptions import (54 FileModeWarning,55 InvalidHeader,56 InvalidURL,57 UnrewindableBodyError,58)59from .structures import CaseInsensitiveDict6061NETRC_FILES = (".netrc", "_netrc")6263DEFAULT_CA_BUNDLE_PATH = certs.where()6465DEFAULT_PORTS = {"http": 80, "https": 443}6667# Ensure that ', ' is used to preserve previous delimiter behavior.68DEFAULT_ACCEPT_ENCODING = ", ".join(69 re.split(r",\s*", make_headers(accept_encoding=True)["accept-encoding"])70)717273if sys.platform == "win32":74 # provide a proxy_bypass version on Windows without DNS lookups7576 def proxy_bypass_registry(host):77 try:78 import winreg79 except ImportError:80 return False8182 try:83 internetSettings = winreg.OpenKey(84 winreg.HKEY_CURRENT_USER,85 r"Software\Microsoft\Windows\CurrentVersion\Internet Settings",86 )87 # ProxyEnable could be REG_SZ or REG_DWORD, normalizing it88 proxyEnable = int(winreg.QueryValueEx(internetSettings, "ProxyEnable")[0])89 # ProxyOverride is almost always a string90 proxyOverride = winreg.QueryValueEx(internetSettings, "ProxyOverride")[0]91 except (OSError, ValueError):92 return False93 if not proxyEnable or not proxyOverride:94 return False9596 # make a check value list from the registry entry: replace the97 # '<local>' string by the localhost entry and the corresponding98 # canonical entry.99 proxyOverride = proxyOverride.split(";")100 # now check if we match one of the registry values.101 for test in proxyOverride:102 if test == "<local>":103 if "." not in host:104 return True105 test = test.replace(".", r"\.") # mask dots106 test = test.replace("*", r".*") # change glob sequence107 test = test.replace("?", r".") # change glob char108 if re.match(test, host, re.I):109 return True110 return False111112 def proxy_bypass(host): # noqa113 """Return True, if the host should be bypassed.114115 Checks proxy settings gathered from the environment, if specified,116 or the registry.117 """118 if getproxies_environment():119 return proxy_bypass_environment(host)120 else:121 return proxy_bypass_registry(host)122123124def dict_to_sequence(d):125 """Returns an internal sequence dictionary update."""126127 if hasattr(d, "items"):128 d = d.items()129130 return d131132133def super_len(o):134 total_length = None135 current_position = 0136137 if hasattr(o, "__len__"):138 total_length = len(o)139140 elif hasattr(o, "len"):141 total_length = o.len142143 elif hasattr(o, "fileno"):144 try:145 fileno = o.fileno()146 except (io.UnsupportedOperation, AttributeError):147 # AttributeError is a surprising exception, seeing as how we've just checked148 # that `hasattr(o, 'fileno')`. It happens for objects obtained via149 # `Tarfile.extractfile()`, per issue 5229.150 pass151 else:152 total_length = os.fstat(fileno).st_size153154 # Having used fstat to determine the file length, we need to155 # confirm that this file was opened up in binary mode.156 if "b" not in o.mode:157 warnings.warn(158 (159 "Requests has determined the content-length for this "160 "request using the binary size of the file: however, the "161 "file has been opened in text mode (i.e. without the 'b' "162 "flag in the mode). This may lead to an incorrect "163 "content-length. In Requests 3.0, support will be removed "164 "for files in text mode."165 ),166 FileModeWarning,167 )168169 if hasattr(o, "tell"):170 try:171 current_position = o.tell()172 except OSError:173 # This can happen in some weird situations, such as when the file174 # is actually a special file descriptor like stdin. In this175 # instance, we don't know what the length is, so set it to zero and176 # let requests chunk it instead.177 if total_length is not None:178 current_position = total_length179 else:180 if hasattr(o, "seek") and total_length is None:181 # StringIO and BytesIO have seek but no usable fileno182 try:183 # seek to end of file184 o.seek(0, 2)185 total_length = o.tell()186187 # seek back to current position to support188 # partially read file-like objects189 o.seek(current_position or 0)190 except OSError:191 total_length = 0192193 if total_length is None:194 total_length = 0195196 return max(0, total_length - current_position)197198199def get_netrc_auth(url, raise_errors=False):200 """Returns the Requests tuple auth for a given url from netrc."""201202 netrc_file = os.environ.get("NETRC")203 if netrc_file is not None:204 netrc_locations = (netrc_file,)205 else:206 netrc_locations = (f"~/{f}" for f in NETRC_FILES)207208 try:209 from netrc import NetrcParseError, netrc210211 netrc_path = None212213 for f in netrc_locations:214 try:215 loc = os.path.expanduser(f)216 except KeyError:217 # os.path.expanduser can fail when $HOME is undefined and218 # getpwuid fails. See https://bugs.python.org/issue20164 &219 # https://github.com/psf/requests/issues/1846220 return221222 if os.path.exists(loc):223 netrc_path = loc224 break225226 # Abort early if there isn't one.227 if netrc_path is None:228 return229230 ri = urlparse(url)231232 # Strip port numbers from netloc. This weird `if...encode`` dance is233 # used for Python 3.2, which doesn't support unicode literals.234 splitstr = b":"235 if isinstance(url, str):236 splitstr = splitstr.decode("ascii")237 host = ri.netloc.split(splitstr)[0]238239 try:240 _netrc = netrc(netrc_path).authenticators(host)241 if _netrc:242 # Return with login / password243 login_i = 0 if _netrc[0] else 1244 return (_netrc[login_i], _netrc[2])245 except (NetrcParseError, OSError):246 # If there was a parsing error or a permissions issue reading the file,247 # we'll just skip netrc auth unless explicitly asked to raise errors.248 if raise_errors:249 raise250251 # App Engine hackiness.252 except (ImportError, AttributeError):253 pass254255256def guess_filename(obj):257 """Tries to guess the filename of the given object."""258 name = getattr(obj, "name", None)259 if name and isinstance(name, basestring) and name[0] != "<" and name[-1] != ">":260 return os.path.basename(name)261262263def extract_zipped_paths(path):264 """Replace nonexistent paths that look like they refer to a member of a zip265 archive with the location of an extracted copy of the target, or else266 just return the provided path unchanged.267 """268 if os.path.exists(path):269 # this is already a valid path, no need to do anything further270 return path271272 # find the first valid part of the provided path and treat that as a zip archive273 # assume the rest of the path is the name of a member in the archive274 archive, member = os.path.split(path)275 while archive and not os.path.exists(archive):276 archive, prefix = os.path.split(archive)277 if not prefix:278 # If we don't check for an empty prefix after the split (in other words, archive remains unchanged after the split),279 # we _can_ end up in an infinite loop on a rare corner case affecting a small number of users280 break281 member = "/".join([prefix, member])282283 if not zipfile.is_zipfile(archive):284 return path285286 zip_file = zipfile.ZipFile(archive)287 if member not in zip_file.namelist():288 return path289290 # we have a valid zip archive and a valid member of that archive291 tmp = tempfile.gettempdir()292 extracted_path = os.path.join(tmp, member.split("/")[-1])293 if not os.path.exists(extracted_path):294 # use read + write to avoid the creating nested folders, we only want the file, avoids mkdir racing condition295 with atomic_open(extracted_path) as file_handler:296 file_handler.write(zip_file.read(member))297 return extracted_path298299300@contextlib.contextmanager301def atomic_open(filename):302 """Write a file to the disk in an atomic fashion"""303 tmp_descriptor, tmp_name = tempfile.mkstemp(dir=os.path.dirname(filename))304 try:305 with os.fdopen(tmp_descriptor, "wb") as tmp_handler:306 yield tmp_handler307 os.replace(tmp_name, filename)308 except BaseException:309 os.remove(tmp_name)310 raise311312313def from_key_val_list(value):314 """Take an object and test to see if it can be represented as a315 dictionary. Unless it can not be represented as such, return an316 OrderedDict, e.g.,317318 ::319320 >>> from_key_val_list([('key', 'val')])321 OrderedDict([('key', 'val')])322 >>> from_key_val_list('string')323 Traceback (most recent call last):324 ...325 ValueError: cannot encode objects that are not 2-tuples326 >>> from_key_val_list({'key': 'val'})327 OrderedDict([('key', 'val')])328329 :rtype: OrderedDict330 """331 if value is None:332 return None333334 if isinstance(value, (str, bytes, bool, int)):335 raise ValueError("cannot encode objects that are not 2-tuples")336337 return OrderedDict(value)338339340def to_key_val_list(value):341 """Take an object and test to see if it can be represented as a342 dictionary. If it can be, return a list of tuples, e.g.,343344 ::345346 >>> to_key_val_list([('key', 'val')])347 [('key', 'val')]348 >>> to_key_val_list({'key': 'val'})349 [('key', 'val')]350 >>> to_key_val_list('string')351 Traceback (most recent call last):352 ...353 ValueError: cannot encode objects that are not 2-tuples354355 :rtype: list356 """357 if value is None:358 return None359360 if isinstance(value, (str, bytes, bool, int)):361 raise ValueError("cannot encode objects that are not 2-tuples")362363 if isinstance(value, Mapping):364 value = value.items()365366 return list(value)367368369# From mitsuhiko/werkzeug (used with permission).370def parse_list_header(value):371 """Parse lists as described by RFC 2068 Section 2.372373 In particular, parse comma-separated lists where the elements of374 the list may include quoted-strings. A quoted-string could375 contain a comma. A non-quoted string could have quotes in the376 middle. Quotes are removed automatically after parsing.377378 It basically works like :func:`parse_set_header` just that items379 may appear multiple times and case sensitivity is preserved.380381 The return value is a standard :class:`list`:382383 >>> parse_list_header('token, "quoted value"')384 ['token', 'quoted value']385386 To create a header from the :class:`list` again, use the387 :func:`dump_header` function.388389 :param value: a string with a list header.390 :return: :class:`list`391 :rtype: list392 """393 result = []394 for item in _parse_list_header(value):395 if item[:1] == item[-1:] == '"':396 item = unquote_header_value(item[1:-1])397 result.append(item)398 return result399400401# From mitsuhiko/werkzeug (used with permission).402def parse_dict_header(value):403 """Parse lists of key, value pairs as described by RFC 2068 Section 2 and404 convert them into a python dict:405406 >>> d = parse_dict_header('foo="is a fish", bar="as well"')407 >>> type(d) is dict408 True409 >>> sorted(d.items())410 [('bar', 'as well'), ('foo', 'is a fish')]411412 If there is no value for a key it will be `None`:413414 >>> parse_dict_header('key_without_value')415 {'key_without_value': None}416417 To create a header from the :class:`dict` again, use the418 :func:`dump_header` function.419420 :param value: a string with a dict header.421 :return: :class:`dict`422 :rtype: dict423 """424 result = {}425 for item in _parse_list_header(value):426 if "=" not in item:427 result[item] = None428 continue429 name, value = item.split("=", 1)430 if value[:1] == value[-1:] == '"':431 value = unquote_header_value(value[1:-1])432 result[name] = value433 return result434435436# From mitsuhiko/werkzeug (used with permission).437def unquote_header_value(value, is_filename=False):438 r"""Unquotes a header value. (Reversal of :func:`quote_header_value`).439 This does not use the real unquoting but what browsers are actually440 using for quoting.441442 :param value: the header value to unquote.443 :rtype: str444 """445 if value and value[0] == value[-1] == '"':446 # this is not the real unquoting, but fixing this so that the447 # RFC is met will result in bugs with internet explorer and448 # probably some other browsers as well. IE for example is449 # uploading files with "C:\foo\bar.txt" as filename450 value = value[1:-1]451452 # if this is a filename and the starting characters look like453 # a UNC path, then just return the value without quotes. Using the454 # replace sequence below on a UNC path has the effect of turning455 # the leading double slash into a single slash and then456 # _fix_ie_filename() doesn't work correctly. See #458.457 if not is_filename or value[:2] != "\\\\":458 return value.replace("\\\\", "\\").replace('\\"', '"')459 return value460461462def dict_from_cookiejar(cj):463 """Returns a key/value dictionary from a CookieJar.464465 :param cj: CookieJar object to extract cookies from.466 :rtype: dict467 """468469 cookie_dict = {cookie.name: cookie.value for cookie in cj}470 return cookie_dict471472473def add_dict_to_cookiejar(cj, cookie_dict):474 """Returns a CookieJar from a key/value dictionary.475476 :param cj: CookieJar to insert cookies into.477 :param cookie_dict: Dict of key/values to insert into CookieJar.478 :rtype: CookieJar479 """480481 return cookiejar_from_dict(cookie_dict, cj)482483484def get_encodings_from_content(content):485 """Returns encodings from given content string.486487 :param content: bytestring to extract encodings from.488 """489 warnings.warn(490 (491 "In requests 3.0, get_encodings_from_content will be removed. For "492 "more information, please see the discussion on issue #2266. (This"493 " warning should only appear once.)"494 ),495 DeprecationWarning,496 )497498 charset_re = re.compile(r'<meta.*?charset=["\']*(.+?)["\'>]', flags=re.I)499 pragma_re = re.compile(r'<meta.*?content=["\']*;?charset=(.+?)["\'>]', flags=re.I)500 xml_re = re.compile(r'^<\?xml.*?encoding=["\']*(.+?)["\'>]')501502 return (503 charset_re.findall(content)504 + pragma_re.findall(content)505 + xml_re.findall(content)506 )507508509def _parse_content_type_header(header):510 """Returns content type and parameters from given header511512 :param header: string513 :return: tuple containing content type and dictionary of514 parameters515 """516517 tokens = header.split(";")518 content_type, params = tokens[0].strip(), tokens[1:]519 params_dict = {}520 items_to_strip = "\"' "521522 for param in params:523 param = param.strip()524 if param:525 key, value = param, True526 index_of_equals = param.find("=")527 if index_of_equals != -1:528 key = param[:index_of_equals].strip(items_to_strip)529 value = param[index_of_equals + 1 :].strip(items_to_strip)530 params_dict[key.lower()] = value531 return content_type, params_dict532533534def get_encoding_from_headers(headers):535 """Returns encodings from given HTTP Header Dict.536537 :param headers: dictionary to extract encoding from.538 :rtype: str539 """540541 content_type = headers.get("content-type")542543 if not content_type:544 return None545546 content_type, params = _parse_content_type_header(content_type)547548 if "charset" in params:549 return params["charset"].strip("'\"")550551 if "text" in content_type:552 return "ISO-8859-1"553554 if "application/json" in content_type:555 # Assume UTF-8 based on RFC 4627: https://www.ietf.org/rfc/rfc4627.txt since the charset was unset556 return "utf-8"557558559def stream_decode_response_unicode(iterator, r):560 """Stream decodes an iterator."""561562 if r.encoding is None:563 yield from iterator564 return565566 decoder = codecs.getincrementaldecoder(r.encoding)(errors="replace")567 for chunk in iterator:568 rv = decoder.decode(chunk)569 if rv:570 yield rv571 rv = decoder.decode(b"", final=True)572 if rv:573 yield rv574575576def iter_slices(string, slice_length):577 """Iterate over slices of a string."""578 pos = 0579 if slice_length is None or slice_length <= 0:580 slice_length = len(string)581 while pos < len(string):582 yield string[pos : pos + slice_length]583 pos += slice_length584585586def get_unicode_from_response(r):587 """Returns the requested content back in unicode.588589 :param r: Response object to get unicode content from.590591 Tried:592593 1. charset from content-type594 2. fall back and replace all unicode characters595596 :rtype: str597 """598 warnings.warn(599 (600 "In requests 3.0, get_unicode_from_response will be removed. For "601 "more information, please see the discussion on issue #2266. (This"602 " warning should only appear once.)"603 ),604 DeprecationWarning,605 )606607 tried_encodings = []608609 # Try charset from content-type610 encoding = get_encoding_from_headers(r.headers)611612 if encoding:613 try:614 return str(r.content, encoding)615 except UnicodeError:616 tried_encodings.append(encoding)617618 # Fall back:619 try:620 return str(r.content, encoding, errors="replace")621 except TypeError:622 return r.content623624625# The unreserved URI characters (RFC 3986)626UNRESERVED_SET = frozenset(627 "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz" + "0123456789-._~"628)629630631def unquote_unreserved(uri):632 """Un-escape any percent-escape sequences in a URI that are unreserved633 characters. This leaves all reserved, illegal and non-ASCII bytes encoded.634635 :rtype: str636 """637 parts = uri.split("%")638 for i in range(1, len(parts)):639 h = parts[i][0:2]640 if len(h) == 2 and h.isalnum():641 try:642 c = chr(int(h, 16))643 except ValueError:644 raise InvalidURL(f"Invalid percent-escape sequence: '{h}'")645646 if c in UNRESERVED_SET:647 parts[i] = c + parts[i][2:]648 else:649 parts[i] = f"%{parts[i]}"650 else:651 parts[i] = f"%{parts[i]}"652 return "".join(parts)653654655def requote_uri(uri):656 """Re-quote the given URI.657658 This function passes the given URI through an unquote/quote cycle to659 ensure that it is fully and consistently quoted.660661 :rtype: str662 """663 safe_with_percent = "!#$%&'()*+,/:;=?@[]~"664 safe_without_percent = "!#$&'()*+,/:;=?@[]~"665 try:666 # Unquote only the unreserved characters667 # Then quote only illegal characters (do not quote reserved,668 # unreserved, or '%')669 return quote(unquote_unreserved(uri), safe=safe_with_percent)670 except InvalidURL:671 # We couldn't unquote the given URI, so let's try quoting it, but672 # there may be unquoted '%'s in the URI. We need to make sure they're673 # properly quoted so they do not cause issues elsewhere.674 return quote(uri, safe=safe_without_percent)675676677def address_in_network(ip, net):678 """This function allows you to check if an IP belongs to a network subnet679680 Example: returns True if ip = 192.168.1.1 and net = 192.168.1.0/24681 returns False if ip = 192.168.1.1 and net = 192.168.100.0/24682683 :rtype: bool684 """685 ipaddr = struct.unpack("=L", socket.inet_aton(ip))[0]686 netaddr, bits = net.split("/")687 netmask = struct.unpack("=L", socket.inet_aton(dotted_netmask(int(bits))))[0]688 network = struct.unpack("=L", socket.inet_aton(netaddr))[0] & netmask689 return (ipaddr & netmask) == (network & netmask)690691692def dotted_netmask(mask):693 """Converts mask from /xx format to xxx.xxx.xxx.xxx694695 Example: if mask is 24 function returns 255.255.255.0696697 :rtype: str698 """699 bits = 0xFFFFFFFF ^ (1 << 32 - mask) - 1700 return socket.inet_ntoa(struct.pack(">I", bits))701702703def is_ipv4_address(string_ip):704 """705 :rtype: bool706 """707 try:708 socket.inet_aton(string_ip)709 except OSError:710 return False711 return True712713714def is_valid_cidr(string_network):715 """716 Very simple check of the cidr format in no_proxy variable.717718 :rtype: bool719 """720 if string_network.count("/") == 1:721 try:722 mask = int(string_network.split("/")[1])723 except ValueError:724 return False725726 if mask < 1 or mask > 32:727 return False728729 try:730 socket.inet_aton(string_network.split("/")[0])731 except OSError:732 return False733 else:734 return False735 return True736737738@contextlib.contextmanager739def set_environ(env_name, value):740 """Set the environment variable 'env_name' to 'value'741742 Save previous value, yield, and then restore the previous value stored in743 the environment variable 'env_name'.744745 If 'value' is None, do nothing"""746 value_changed = value is not None747 if value_changed:748 old_value = os.environ.get(env_name)749 os.environ[env_name] = value750 try:751 yield752 finally:753 if value_changed:754 if old_value is None:755 del os.environ[env_name]756 else:757 os.environ[env_name] = old_value758759760def should_bypass_proxies(url, no_proxy):761 """762 Returns whether we should bypass proxies or not.763764 :rtype: bool765 """766767 # Prioritize lowercase environment variables over uppercase768 # to keep a consistent behaviour with other http projects (curl, wget).769 def get_proxy(key):770 return os.environ.get(key) or os.environ.get(key.upper())771772 # First check whether no_proxy is defined. If it is, check that the URL773 # we're getting isn't in the no_proxy list.774 no_proxy_arg = no_proxy775 if no_proxy is None:776 no_proxy = get_proxy("no_proxy")777 parsed = urlparse(url)778779 if parsed.hostname is None:780 # URLs don't always have hostnames, e.g. file:/// urls.781 return True782783 if no_proxy:784 # We need to check whether we match here. We need to see if we match785 # the end of the hostname, both with and without the port.786 no_proxy = (host for host in no_proxy.replace(" ", "").split(",") if host)787788 if is_ipv4_address(parsed.hostname):789 for proxy_ip in no_proxy:790 if is_valid_cidr(proxy_ip):791 if address_in_network(parsed.hostname, proxy_ip):792 return True793 elif parsed.hostname == proxy_ip:794 # If no_proxy ip was defined in plain IP notation instead of cidr notation &795 # matches the IP of the index796 return True797 else:798 host_with_port = parsed.hostname799 if parsed.port:800 host_with_port += f":{parsed.port}"801802 for host in no_proxy:803 if parsed.hostname.endswith(host) or host_with_port.endswith(host):804 # The URL does match something in no_proxy, so we don't want805 # to apply the proxies on this URL.806 return True807808 with set_environ("no_proxy", no_proxy_arg):809 # parsed.hostname can be `None` in cases such as a file URI.810 try:811 bypass = proxy_bypass(parsed.hostname)812 except (TypeError, socket.gaierror):813 bypass = False814815 if bypass:816 return True817818 return False819820821def get_environ_proxies(url, no_proxy=None):822 """823 Return a dict of environment proxies.824825 :rtype: dict826 """827 if should_bypass_proxies(url, no_proxy=no_proxy):828 return {}829 else:830 return getproxies()831832833def select_proxy(url, proxies):834 """Select a proxy for the url, if applicable.835836 :param url: The url being for the request837 :param proxies: A dictionary of schemes or schemes and hosts to proxy URLs838 """839 proxies = proxies or {}840 urlparts = urlparse(url)841 if urlparts.hostname is None:842 return proxies.get(urlparts.scheme, proxies.get("all"))843844 proxy_keys = [845 urlparts.scheme + "://" + urlparts.hostname,846 urlparts.scheme,847 "all://" + urlparts.hostname,848 "all",849 ]850 proxy = None851 for proxy_key in proxy_keys:852 if proxy_key in proxies:853 proxy = proxies[proxy_key]854 break855856 return proxy857858859def resolve_proxies(request, proxies, trust_env=True):860 """This method takes proxy information from a request and configuration861 input to resolve a mapping of target proxies. This will consider settings862 such a NO_PROXY to strip proxy configurations.863864 :param request: Request or PreparedRequest865 :param proxies: A dictionary of schemes or schemes and hosts to proxy URLs866 :param trust_env: Boolean declaring whether to trust environment configs867868 :rtype: dict869 """870 proxies = proxies if proxies is not None else {}871 url = request.url872 scheme = urlparse(url).scheme873 no_proxy = proxies.get("no_proxy")874 new_proxies = proxies.copy()875876 if trust_env and not should_bypass_proxies(url, no_proxy=no_proxy):877 environ_proxies = get_environ_proxies(url, no_proxy=no_proxy)878879 proxy = environ_proxies.get(scheme, environ_proxies.get("all"))880881 if proxy:882 new_proxies.setdefault(scheme, proxy)883 return new_proxies884885886def default_user_agent(name="python-requests"):887 """888 Return a string representing the default user agent.889890 :rtype: str891 """892 return f"{name}/{__version__}"893894895def default_headers():896 """897 :rtype: requests.structures.CaseInsensitiveDict898 """899 return CaseInsensitiveDict(900 {901 "User-Agent": default_user_agent(),902 "Accept-Encoding": DEFAULT_ACCEPT_ENCODING,903 "Accept": "*/*",904 "Connection": "keep-alive",905 }906 )907908909def parse_header_links(value):910 """Return a list of parsed link headers proxies.911912 i.e. Link: <http:/.../front.jpeg>; rel=front; type="image/jpeg",<http://.../back.jpeg>; rel=back;type="image/jpeg"913914 :rtype: list915 """916917 links = []918919 replace_chars = " '\""920921 value = value.strip(replace_chars)922 if not value:923 return links924925 for val in re.split(", *<", value):926 try:927 url, params = val.split(";", 1)928 except ValueError:929 url, params = val, ""930931 link = {"url": url.strip("<> '\"")}932933 for param in params.split(";"):934 try:935 key, value = param.split("=")936 except ValueError:937 break938939 link[key.strip(replace_chars)] = value.strip(replace_chars)940941 links.append(link)942943 return links944945946# Null bytes; no need to recreate these on each call to guess_json_utf947_null = "\x00".encode("ascii") # encoding to ASCII for Python 3948_null2 = _null * 2949_null3 = _null * 3950951952def guess_json_utf(data):953 """954 :rtype: str955 """956 # JSON always starts with two ASCII characters, so detection is as957 # easy as counting the nulls and from their location and count958 # determine the encoding. Also detect a BOM, if present.959 sample = data[:4]960 if sample in (codecs.BOM_UTF32_LE, codecs.BOM_UTF32_BE):961 return "utf-32" # BOM included962 if sample[:3] == codecs.BOM_UTF8:963 return "utf-8-sig" # BOM included, MS style (discouraged)964 if sample[:2] in (codecs.BOM_UTF16_LE, codecs.BOM_UTF16_BE):965 return "utf-16" # BOM included966 nullcount = sample.count(_null)967 if nullcount == 0:968 return "utf-8"969 if nullcount == 2:970 if sample[::2] == _null2: # 1st and 3rd are null971 return "utf-16-be"972 if sample[1::2] == _null2: # 2nd and 4th are null973 return "utf-16-le"974 # Did not detect 2 valid UTF-16 ascii-range characters975 if nullcount == 3:976 if sample[:3] == _null3:977 return "utf-32-be"978 if sample[1:] == _null3:979 return "utf-32-le"980 # Did not detect a valid UTF-32 ascii-range character981 return None982983984def prepend_scheme_if_needed(url, new_scheme):985 """Given a URL that may or may not have a scheme, prepend the given scheme.986 Does not replace a present scheme with the one provided as an argument.987988 :rtype: str989 """990 parsed = parse_url(url)991 scheme, auth, host, port, path, query, fragment = parsed992993 # A defect in urlparse determines that there isn't a netloc present in some994 # urls. We previously assumed parsing was overly cautious, and swapped the995 # netloc and path. Due to a lack of tests on the original defect, this is996 # maintained with parse_url for backwards compatibility.997 netloc = parsed.netloc998 if not netloc:999 netloc, path = path, netloc10001001 if auth:1002 # parse_url doesn't provide the netloc with auth1003 # so we'll add it ourselves.1004 netloc = "@".join([auth, netloc])1005 if scheme is None:1006 scheme = new_scheme1007 if path is None:1008 path = ""10091010 return urlunparse((scheme, netloc, path, "", query, fragment))101110121013def get_auth_from_url(url):1014 """Given a url with authentication components, extract them into a tuple of1015 username,password.10161017 :rtype: (str,str)1018 """1019 parsed = urlparse(url)10201021 try:1022 auth = (unquote(parsed.username), unquote(parsed.password))1023 except (AttributeError, TypeError):1024 auth = ("", "")10251026 return auth102710281029def check_header_validity(header):1030 """Verifies that header parts don't contain leading whitespace1031 reserved characters, or return characters.10321033 :param header: tuple, in the format (name, value).1034 """1035 name, value = header1036 _validate_header_part(header, name, 0)1037 _validate_header_part(header, value, 1)103810391040def _validate_header_part(header, header_part, header_validator_index):1041 if isinstance(header_part, str):1042 validator = _HEADER_VALIDATORS_STR[header_validator_index]1043 elif isinstance(header_part, bytes):1044 validator = _HEADER_VALIDATORS_BYTE[header_validator_index]1045 else:1046 raise InvalidHeader(1047 f"Header part ({header_part!r}) from {header} "1048 f"must be of type str or bytes, not {type(header_part)}"1049 )10501051 if not validator.match(header_part):1052 header_kind = "name" if header_validator_index == 0 else "value"1053 raise InvalidHeader(1054 f"Invalid leading whitespace, reserved character(s), or return"1055 f"character(s) in header {header_kind}: {header_part!r}"1056 )105710581059def urldefragauth(url):1060 """1061 Given a url remove the fragment and the authentication part.10621063 :rtype: str1064 """1065 scheme, netloc, path, params, query, fragment = urlparse(url)10661067 # see func:`prepend_scheme_if_needed`1068 if not netloc:1069 netloc, path = path, netloc10701071 netloc = netloc.rsplit("@", 1)[-1]10721073 return urlunparse((scheme, netloc, path, params, query, ""))107410751076def rewind_body(prepared_request):1077 """Move file pointer back to its recorded starting position1078 so it can be read again on redirect.1079 """1080 body_seek = getattr(prepared_request.body, "seek", None)1081 if body_seek is not None and isinstance(1082 prepared_request._body_position, integer_types1083 ):1084 try:1085 body_seek(prepared_request._body_position)1086 except OSError:1087 raise UnrewindableBodyError(1088 "An error occurred when rewinding request body for redirect."1089 )1090 else:1091 raise UnrewindableBodyError("Unable to rewind request body for redirect.")
added:src/requests/__init__.py+180 added
1# __2# /__) _ _ _ _ _/ _3# / ( (- (/ (/ (- _) / _)4# /56"""7Requests HTTP Library8~~~~~~~~~~~~~~~~~~~~~910Requests is an HTTP library, written in Python, for human beings.11Basic GET usage:1213 >>> import requests14 >>> r = requests.get('https://www.python.org')15 >>> r.status_code16 20017 >>> b'Python is a programming language' in r.content18 True1920... or POST:2122 >>> payload = dict(key1='value1', key2='value2')23 >>> r = requests.post('https://httpbin.org/post', data=payload)24 >>> print(r.text)25 {26 ...27 "form": {28 "key1": "value1",29 "key2": "value2"30 },31 ...32 }3334The other HTTP methods are supported - see `requests.api`. Full documentation35is at <https://requests.readthedocs.io>.3637:copyright: (c) 2017 by Kenneth Reitz.38:license: Apache 2.0, see LICENSE for more details.39"""4041import warnings4243import urllib34445from .exceptions import RequestsDependencyWarning4647try:48 from charset_normalizer import __version__ as charset_normalizer_version49except ImportError:50 charset_normalizer_version = None5152try:53 from chardet import __version__ as chardet_version54except ImportError:55 chardet_version = None565758def check_compatibility(urllib3_version, chardet_version, charset_normalizer_version):59 urllib3_version = urllib3_version.split(".")60 assert urllib3_version != ["dev"] # Verify urllib3 isn't installed from git.6162 # Sometimes, urllib3 only reports its version as 16.1.63 if len(urllib3_version) == 2:64 urllib3_version.append("0")6566 # Check urllib3 for compatibility.67 major, minor, patch = urllib3_version # noqa: F81168 major, minor, patch = int(major), int(minor), int(patch)69 # urllib3 >= 1.21.170 assert major >= 171 if major == 1:72 assert minor >= 217374 # Check charset_normalizer for compatibility.75 if chardet_version:76 major, minor, patch = chardet_version.split(".")[:3]77 major, minor, patch = int(major), int(minor), int(patch)78 # chardet_version >= 3.0.2, < 6.0.079 assert (3, 0, 2) <= (major, minor, patch) < (6, 0, 0)80 elif charset_normalizer_version:81 major, minor, patch = charset_normalizer_version.split(".")[:3]82 major, minor, patch = int(major), int(minor), int(patch)83 # charset_normalizer >= 2.0.0 < 4.0.084 assert (2, 0, 0) <= (major, minor, patch) < (4, 0, 0)85 else:86 raise Exception("You need either charset_normalizer or chardet installed")878889def _check_cryptography(cryptography_version):90 # cryptography < 1.3.491 try:92 cryptography_version = list(map(int, cryptography_version.split(".")))93 except ValueError:94 return9596 if cryptography_version < [1, 3, 4]:97 warning = "Old version of cryptography ({}) may cause slowdown.".format(98 cryptography_version99 )100 warnings.warn(warning, RequestsDependencyWarning)101102103# Check imported dependencies for compatibility.104try:105 check_compatibility(106 urllib3.__version__, chardet_version, charset_normalizer_version107 )108except (AssertionError, ValueError):109 warnings.warn(110 "urllib3 ({}) or chardet ({})/charset_normalizer ({}) doesn't match a supported "111 "version!".format(112 urllib3.__version__, chardet_version, charset_normalizer_version113 ),114 RequestsDependencyWarning,115 )116117# Attempt to enable urllib3's fallback for SNI support118# if the standard library doesn't support SNI or the119# 'ssl' library isn't available.120try:121 try:122 import ssl123 except ImportError:124 ssl = None125126 if not getattr(ssl, "HAS_SNI", False):127 from urllib3.contrib import pyopenssl128129 pyopenssl.inject_into_urllib3()130131 # Check cryptography version132 from cryptography import __version__ as cryptography_version133134 _check_cryptography(cryptography_version)135except ImportError:136 pass137138# urllib3's DependencyWarnings should be silenced.139from urllib3.exceptions import DependencyWarning140141warnings.simplefilter("ignore", DependencyWarning)142143# Set default logging handler to avoid "No handler found" warnings.144import logging145from logging import NullHandler146147from . import packages, utils148from .__version__ import (149 __author__,150 __author_email__,151 __build__,152 __cake__,153 __copyright__,154 __description__,155 __license__,156 __title__,157 __url__,158 __version__,159)160from .api import delete, get, head, options, patch, post, put, request161from .exceptions import (162 ConnectionError,163 ConnectTimeout,164 FileModeWarning,165 HTTPError,166 JSONDecodeError,167 ReadTimeout,168 RequestException,169 Timeout,170 TooManyRedirects,171 URLRequired,172)173from .models import PreparedRequest, Request, Response174from .sessions import Session, session175from .status_codes import codes176177logging.getLogger(__name__).addHandler(NullHandler())178179# FileModeWarnings go off per the default.180warnings.simplefilter("default", FileModeWarning, append=True)
added:src/requests/__version__.py+14 added
1# .-. .-. .-. . . .-. .-. .-. .-.2# |( |- |.| | | |- `-. | `-.3# ' ' `-' `-`.`-' `-' `-' ' `-'45__title__ = "requests"6__description__ = "Python HTTP for Humans."7__url__ = "https://requests.readthedocs.io"8__version__ = "2.31.0"9__build__ = 0x02310010__author__ = "Kenneth Reitz"11__author_email__ = "me@kennethreitz.org"12__license__ = "Apache-2.0"13__copyright__ = "Copyright Kenneth Reitz"14__cake__ = "\u2728 \U0001f370 \u2728"
added:src/requests/_internal_utils.py+50 added
1"""2requests._internal_utils3~~~~~~~~~~~~~~45Provides utility functions that are consumed internally by Requests6which depend on extremely few external helpers (such as compat)7"""8import re910from .compat import builtin_str1112_VALID_HEADER_NAME_RE_BYTE = re.compile(rb"^[^:\s][^:\r\n]*$")13_VALID_HEADER_NAME_RE_STR = re.compile(r"^[^:\s][^:\r\n]*$")14_VALID_HEADER_VALUE_RE_BYTE = re.compile(rb"^\S[^\r\n]*$|^$")15_VALID_HEADER_VALUE_RE_STR = re.compile(r"^\S[^\r\n]*$|^$")1617_HEADER_VALIDATORS_STR = (_VALID_HEADER_NAME_RE_STR, _VALID_HEADER_VALUE_RE_STR)18_HEADER_VALIDATORS_BYTE = (_VALID_HEADER_NAME_RE_BYTE, _VALID_HEADER_VALUE_RE_BYTE)19HEADER_VALIDATORS = {20 bytes: _HEADER_VALIDATORS_BYTE,21 str: _HEADER_VALIDATORS_STR,22}232425def to_native_string(string, encoding="ascii"):26 """Given a string object, regardless of type, returns a representation of27 that string in the native string type, encoding and decoding where28 necessary. This assumes ASCII unless told otherwise.29 """30 if isinstance(string, builtin_str):31 out = string32 else:33 out = string.decode(encoding)3435 return out363738def unicode_is_ascii(u_string):39 """Determine if unicode string only contains ASCII characters.4041 :param str u_string: unicode string to check. Must be unicode42 and not Python 2 `str`.43 :rtype: bool44 """45 assert isinstance(u_string, str)46 try:47 u_string.encode("ascii")48 return True49 except UnicodeEncodeError:50 return False
added:src/requests/adapters.py+537 added
1"""2requests.adapters3~~~~~~~~~~~~~~~~~45This module contains the transport adapters that Requests uses to define6and maintain connections.7"""89import os.path10import socket # noqa: F4011112from urllib3.exceptions import ClosedPoolError, ConnectTimeoutError13from urllib3.exceptions import HTTPError as _HTTPError14from urllib3.exceptions import InvalidHeader as _InvalidHeader15from urllib3.exceptions import (16 LocationValueError,17 MaxRetryError,18 NewConnectionError,19 ProtocolError,20)21from urllib3.exceptions import ProxyError as _ProxyError22from urllib3.exceptions import ReadTimeoutError, ResponseError23from urllib3.exceptions import SSLError as _SSLError24from urllib3.poolmanager import PoolManager, proxy_from_url25from urllib3.util import Timeout as TimeoutSauce26from urllib3.util import parse_url27from urllib3.util.retry import Retry2829from .auth import _basic_auth_str30from .compat import basestring, urlparse31from .cookies import extract_cookies_to_jar32from .exceptions import (33 ConnectionError,34 ConnectTimeout,35 InvalidHeader,36 InvalidProxyURL,37 InvalidSchema,38 InvalidURL,39 ProxyError,40 ReadTimeout,41 RetryError,42 SSLError,43)44from .models import Response45from .structures import CaseInsensitiveDict46from .utils import (47 DEFAULT_CA_BUNDLE_PATH,48 extract_zipped_paths,49 get_auth_from_url,50 get_encoding_from_headers,51 prepend_scheme_if_needed,52 select_proxy,53 urldefragauth,54)5556try:57 from urllib3.contrib.socks import SOCKSProxyManager58except ImportError:5960 def SOCKSProxyManager(*args, **kwargs):61 raise InvalidSchema("Missing dependencies for SOCKS support.")626364DEFAULT_POOLBLOCK = False65DEFAULT_POOLSIZE = 1066DEFAULT_RETRIES = 067DEFAULT_POOL_TIMEOUT = None686970class BaseAdapter:71 """The Base Transport Adapter"""7273 def __init__(self):74 super().__init__()7576 def send(77 self, request, stream=False, timeout=None, verify=True, cert=None, proxies=None78 ):79 """Sends PreparedRequest object. Returns Response object.8081 :param request: The :class:`PreparedRequest <PreparedRequest>` being sent.82 :param stream: (optional) Whether to stream the request content.83 :param timeout: (optional) How long to wait for the server to send84 data before giving up, as a float, or a :ref:`(connect timeout,85 read timeout) <timeouts>` tuple.86 :type timeout: float or tuple87 :param verify: (optional) Either a boolean, in which case it controls whether we verify88 the server's TLS certificate, or a string, in which case it must be a path89 to a CA bundle to use90 :param cert: (optional) Any user-provided SSL certificate to be trusted.91 :param proxies: (optional) The proxies dictionary to apply to the request.92 """93 raise NotImplementedError9495 def close(self):96 """Cleans up adapter specific items."""97 raise NotImplementedError9899100class HTTPAdapter(BaseAdapter):101 """The built-in HTTP Adapter for urllib3.102103 Provides a general-case interface for Requests sessions to contact HTTP and104 HTTPS urls by implementing the Transport Adapter interface. This class will105 usually be created by the :class:`Session <Session>` class under the106 covers.107108 :param pool_connections: The number of urllib3 connection pools to cache.109 :param pool_maxsize: The maximum number of connections to save in the pool.110 :param max_retries: The maximum number of retries each connection111 should attempt. Note, this applies only to failed DNS lookups, socket112 connections and connection timeouts, never to requests where data has113 made it to the server. By default, Requests does not retry failed114 connections. If you need granular control over the conditions under115 which we retry a request, import urllib3's ``Retry`` class and pass116 that instead.117 :param pool_block: Whether the connection pool should block for connections.118119 Usage::120121 >>> import requests122 >>> s = requests.Session()123 >>> a = requests.adapters.HTTPAdapter(max_retries=3)124 >>> s.mount('http://', a)125 """126127 __attrs__ = [128 "max_retries",129 "config",130 "_pool_connections",131 "_pool_maxsize",132 "_pool_block",133 ]134135 def __init__(136 self,137 pool_connections=DEFAULT_POOLSIZE,138 pool_maxsize=DEFAULT_POOLSIZE,139 max_retries=DEFAULT_RETRIES,140 pool_block=DEFAULT_POOLBLOCK,141 ):142 if max_retries == DEFAULT_RETRIES:143 self.max_retries = Retry(0, read=False)144 else:145 self.max_retries = Retry.from_int(max_retries)146 self.config = {}147 self.proxy_manager = {}148149 super().__init__()150151 self._pool_connections = pool_connections152 self._pool_maxsize = pool_maxsize153 self._pool_block = pool_block154155 self.init_poolmanager(pool_connections, pool_maxsize, block=pool_block)156157 def __getstate__(self):158 return {attr: getattr(self, attr, None) for attr in self.__attrs__}159160 def __setstate__(self, state):161 # Can't handle by adding 'proxy_manager' to self.__attrs__ because162 # self.poolmanager uses a lambda function, which isn't pickleable.163 self.proxy_manager = {}164 self.config = {}165166 for attr, value in state.items():167 setattr(self, attr, value)168169 self.init_poolmanager(170 self._pool_connections, self._pool_maxsize, block=self._pool_block171 )172173 def init_poolmanager(174 self, connections, maxsize, block=DEFAULT_POOLBLOCK, **pool_kwargs175 ):176 """Initializes a urllib3 PoolManager.177178 This method should not be called from user code, and is only179 exposed for use when subclassing the180 :class:`HTTPAdapter <requests.adapters.HTTPAdapter>`.181182 :param connections: The number of urllib3 connection pools to cache.183 :param maxsize: The maximum number of connections to save in the pool.184 :param block: Block when no free connections are available.185 :param pool_kwargs: Extra keyword arguments used to initialize the Pool Manager.186 """187 # save these values for pickling188 self._pool_connections = connections189 self._pool_maxsize = maxsize190 self._pool_block = block191192 self.poolmanager = PoolManager(193 num_pools=connections,194 maxsize=maxsize,195 block=block,196 **pool_kwargs,197 )198199 def proxy_manager_for(self, proxy, **proxy_kwargs):200 """Return urllib3 ProxyManager for the given proxy.201202 This method should not be called from user code, and is only203 exposed for use when subclassing the204 :class:`HTTPAdapter <requests.adapters.HTTPAdapter>`.205206 :param proxy: The proxy to return a urllib3 ProxyManager for.207 :param proxy_kwargs: Extra keyword arguments used to configure the Proxy Manager.208 :returns: ProxyManager209 :rtype: urllib3.ProxyManager210 """211 if proxy in self.proxy_manager:212 manager = self.proxy_manager[proxy]213 elif proxy.lower().startswith("socks"):214 username, password = get_auth_from_url(proxy)215 manager = self.proxy_manager[proxy] = SOCKSProxyManager(216 proxy,217 username=username,218 password=password,219 num_pools=self._pool_connections,220 maxsize=self._pool_maxsize,221 block=self._pool_block,222 **proxy_kwargs,223 )224 else:225 proxy_headers = self.proxy_headers(proxy)226 manager = self.proxy_manager[proxy] = proxy_from_url(227 proxy,228 proxy_headers=proxy_headers,229 num_pools=self._pool_connections,230 maxsize=self._pool_maxsize,231 block=self._pool_block,232 **proxy_kwargs,233 )234235 return manager236237 def cert_verify(self, conn, url, verify, cert):238 """Verify a SSL certificate. This method should not be called from user239 code, and is only exposed for use when subclassing the240 :class:`HTTPAdapter <requests.adapters.HTTPAdapter>`.241242 :param conn: The urllib3 connection object associated with the cert.243 :param url: The requested URL.244 :param verify: Either a boolean, in which case it controls whether we verify245 the server's TLS certificate, or a string, in which case it must be a path246 to a CA bundle to use247 :param cert: The SSL certificate to verify.248 """249 if url.lower().startswith("https") and verify:250 cert_loc = None251252 # Allow self-specified cert location.253 if verify is not True:254 cert_loc = verify255256 if not cert_loc:257 cert_loc = extract_zipped_paths(DEFAULT_CA_BUNDLE_PATH)258259 if not cert_loc or not os.path.exists(cert_loc):260 raise OSError(261 f"Could not find a suitable TLS CA certificate bundle, "262 f"invalid path: {cert_loc}"263 )264265 conn.cert_reqs = "CERT_REQUIRED"266267 if not os.path.isdir(cert_loc):268 conn.ca_certs = cert_loc269 else:270 conn.ca_cert_dir = cert_loc271 else:272 conn.cert_reqs = "CERT_NONE"273 conn.ca_certs = None274 conn.ca_cert_dir = None275276 if cert:277 if not isinstance(cert, basestring):278 conn.cert_file = cert[0]279 conn.key_file = cert[1]280 else:281 conn.cert_file = cert282 conn.key_file = None283 if conn.cert_file and not os.path.exists(conn.cert_file):284 raise OSError(285 f"Could not find the TLS certificate file, "286 f"invalid path: {conn.cert_file}"287 )288 if conn.key_file and not os.path.exists(conn.key_file):289 raise OSError(290 f"Could not find the TLS key file, invalid path: {conn.key_file}"291 )292293 def build_response(self, req, resp):294 """Builds a :class:`Response <requests.Response>` object from a urllib3295 response. This should not be called from user code, and is only exposed296 for use when subclassing the297 :class:`HTTPAdapter <requests.adapters.HTTPAdapter>`298299 :param req: The :class:`PreparedRequest <PreparedRequest>` used to generate the response.300 :param resp: The urllib3 response object.301 :rtype: requests.Response302 """303 response = Response()304305 # Fallback to None if there's no status_code, for whatever reason.306 response.status_code = getattr(resp, "status", None)307308 # Make headers case-insensitive.309 response.headers = CaseInsensitiveDict(getattr(resp, "headers", {}))310311 # Set encoding.312 response.encoding = get_encoding_from_headers(response.headers)313 response.raw = resp314 response.reason = response.raw.reason315316 if isinstance(req.url, bytes):317 response.url = req.url.decode("utf-8")318 else:319 response.url = req.url320321 # Add new cookies from the server.322 extract_cookies_to_jar(response.cookies, req, resp)323324 # Give the Response some context.325 response.request = req326 response.connection = self327328 return response329330 def get_connection(self, url, proxies=None):331 """Returns a urllib3 connection for the given URL. This should not be332 called from user code, and is only exposed for use when subclassing the333 :class:`HTTPAdapter <requests.adapters.HTTPAdapter>`.334335 :param url: The URL to connect to.336 :param proxies: (optional) A Requests-style dictionary of proxies used on this request.337 :rtype: urllib3.ConnectionPool338 """339 proxy = select_proxy(url, proxies)340341 if proxy:342 proxy = prepend_scheme_if_needed(proxy, "http")343 proxy_url = parse_url(proxy)344 if not proxy_url.host:345 raise InvalidProxyURL(346 "Please check proxy URL. It is malformed "347 "and could be missing the host."348 )349 proxy_manager = self.proxy_manager_for(proxy)350 conn = proxy_manager.connection_from_url(url)351 else:352 # Only scheme should be lower case353 parsed = urlparse(url)354 url = parsed.geturl()355 conn = self.poolmanager.connection_from_url(url)356357 return conn358359 def close(self):360 """Disposes of any internal state.361362 Currently, this closes the PoolManager and any active ProxyManager,363 which closes any pooled connections.364 """365 self.poolmanager.clear()366 for proxy in self.proxy_manager.values():367 proxy.clear()368369 def request_url(self, request, proxies):370 """Obtain the url to use when making the final request.371372 If the message is being sent through a HTTP proxy, the full URL has to373 be used. Otherwise, we should only use the path portion of the URL.374375 This should not be called from user code, and is only exposed for use376 when subclassing the377 :class:`HTTPAdapter <requests.adapters.HTTPAdapter>`.378379 :param request: The :class:`PreparedRequest <PreparedRequest>` being sent.380 :param proxies: A dictionary of schemes or schemes and hosts to proxy URLs.381 :rtype: str382 """383 proxy = select_proxy(request.url, proxies)384 scheme = urlparse(request.url).scheme385386 is_proxied_http_request = proxy and scheme != "https"387 using_socks_proxy = False388 if proxy:389 proxy_scheme = urlparse(proxy).scheme.lower()390 using_socks_proxy = proxy_scheme.startswith("socks")391392 url = request.path_url393 if is_proxied_http_request and not using_socks_proxy:394 url = urldefragauth(request.url)395396 return url397398 def add_headers(self, request, **kwargs):399 """Add any headers needed by the connection. As of v2.0 this does400 nothing by default, but is left for overriding by users that subclass401 the :class:`HTTPAdapter <requests.adapters.HTTPAdapter>`.402403 This should not be called from user code, and is only exposed for use404 when subclassing the405 :class:`HTTPAdapter <requests.adapters.HTTPAdapter>`.406407 :param request: The :class:`PreparedRequest <PreparedRequest>` to add headers to.408 :param kwargs: The keyword arguments from the call to send().409 """410 pass411412 def proxy_headers(self, proxy):413 """Returns a dictionary of the headers to add to any request sent414 through a proxy. This works with urllib3 magic to ensure that they are415 correctly sent to the proxy, rather than in a tunnelled request if416 CONNECT is being used.417418 This should not be called from user code, and is only exposed for use419 when subclassing the420 :class:`HTTPAdapter <requests.adapters.HTTPAdapter>`.421422 :param proxy: The url of the proxy being used for this request.423 :rtype: dict424 """425 headers = {}426 username, password = get_auth_from_url(proxy)427428 if username:429 headers["Proxy-Authorization"] = _basic_auth_str(username, password)430431 return headers432433 def send(434 self, request, stream=False, timeout=None, verify=True, cert=None, proxies=None435 ):436 """Sends PreparedRequest object. Returns Response object.437438 :param request: The :class:`PreparedRequest <PreparedRequest>` being sent.439 :param stream: (optional) Whether to stream the request content.440 :param timeout: (optional) How long to wait for the server to send441 data before giving up, as a float, or a :ref:`(connect timeout,442 read timeout) <timeouts>` tuple.443 :type timeout: float or tuple or urllib3 Timeout object444 :param verify: (optional) Either a boolean, in which case it controls whether445 we verify the server's TLS certificate, or a string, in which case it446 must be a path to a CA bundle to use447 :param cert: (optional) Any user-provided SSL certificate to be trusted.448 :param proxies: (optional) The proxies dictionary to apply to the request.449 :rtype: requests.Response450 """451452 try:453 conn = self.get_connection(request.url, proxies)454 except LocationValueError as e:455 raise InvalidURL(e, request=request)456457 self.cert_verify(conn, request.url, verify, cert)458 url = self.request_url(request, proxies)459 self.add_headers(460 request,461 stream=stream,462 timeout=timeout,463 verify=verify,464 cert=cert,465 proxies=proxies,466 )467468 chunked = not (request.body is None or "Content-Length" in request.headers)469470 if isinstance(timeout, tuple):471 try:472 connect, read = timeout473 timeout = TimeoutSauce(connect=connect, read=read)474 except ValueError:475 raise ValueError(476 f"Invalid timeout {timeout}. Pass a (connect, read) timeout tuple, "477 f"or a single float to set both timeouts to the same value."478 )479 elif isinstance(timeout, TimeoutSauce):480 pass481 else:482 timeout = TimeoutSauce(connect=timeout, read=timeout)483484 try:485 resp = conn.urlopen(486 method=request.method,487 url=url,488 body=request.body,489 headers=request.headers,490 redirect=False,491 assert_same_host=False,492 preload_content=False,493 decode_content=False,494 retries=self.max_retries,495 timeout=timeout,496 chunked=chunked,497 )498499 except (ProtocolError, OSError) as err:500 raise ConnectionError(err, request=request)501502 except MaxRetryError as e:503 if isinstance(e.reason, ConnectTimeoutError):504 # TODO: Remove this in 3.0.0: see #2811505 if not isinstance(e.reason, NewConnectionError):506 raise ConnectTimeout(e, request=request)507508 if isinstance(e.reason, ResponseError):509 raise RetryError(e, request=request)510511 if isinstance(e.reason, _ProxyError):512 raise ProxyError(e, request=request)513514 if isinstance(e.reason, _SSLError):515 # This branch is for urllib3 v1.22 and later.516 raise SSLError(e, request=request)517518 raise ConnectionError(e, request=request)519520 except ClosedPoolError as e:521 raise ConnectionError(e, request=request)522523 except _ProxyError as e:524 raise ProxyError(e)525526 except (_SSLError, _HTTPError) as e:527 if isinstance(e, _SSLError):528 # This branch is for urllib3 versions earlier than v1.22529 raise SSLError(e, request=request)530 elif isinstance(e, ReadTimeoutError):531 raise ReadTimeout(e, request=request)532 elif isinstance(e, _InvalidHeader):533 raise InvalidHeader(e, request=request)534 else:535 raise536537 return self.build_response(request, resp)
added:src/requests/api.py+157 added
1"""2requests.api3~~~~~~~~~~~~45This module implements the Requests API.67:copyright: (c) 2012 by Kenneth Reitz.8:license: Apache2, see LICENSE for more details.9"""1011from . import sessions121314def request(method, url, **kwargs):15 """Constructs and sends a :class:`Request <Request>`.1617 :param method: method for the new :class:`Request` object: ``GET``, ``OPTIONS``, ``HEAD``, ``POST``, ``PUT``, ``PATCH``, or ``DELETE``.18 :param url: URL for the new :class:`Request` object.19 :param params: (optional) Dictionary, list of tuples or bytes to send20 in the query string for the :class:`Request`.21 :param data: (optional) Dictionary, list of tuples, bytes, or file-like22 object to send in the body of the :class:`Request`.23 :param json: (optional) A JSON serializable Python object to send in the body of the :class:`Request`.24 :param headers: (optional) Dictionary of HTTP Headers to send with the :class:`Request`.25 :param cookies: (optional) Dict or CookieJar object to send with the :class:`Request`.26 :param files: (optional) Dictionary of ``'name': file-like-objects`` (or ``{'name': file-tuple}``) for multipart encoding upload.27 ``file-tuple`` can be a 2-tuple ``('filename', fileobj)``, 3-tuple ``('filename', fileobj, 'content_type')``28 or a 4-tuple ``('filename', fileobj, 'content_type', custom_headers)``, where ``'content_type'`` is a string29 defining the content type of the given file and ``custom_headers`` a dict-like object containing additional headers30 to add for the file.31 :param auth: (optional) Auth tuple to enable Basic/Digest/Custom HTTP Auth.32 :param timeout: (optional) How many seconds to wait for the server to send data33 before giving up, as a float, or a :ref:`(connect timeout, read34 timeout) <timeouts>` tuple.35 :type timeout: float or tuple36 :param allow_redirects: (optional) Boolean. Enable/disable GET/OPTIONS/POST/PUT/PATCH/DELETE/HEAD redirection. Defaults to ``True``.37 :type allow_redirects: bool38 :param proxies: (optional) Dictionary mapping protocol to the URL of the proxy.39 :param verify: (optional) Either a boolean, in which case it controls whether we verify40 the server's TLS certificate, or a string, in which case it must be a path41 to a CA bundle to use. Defaults to ``True``.42 :param stream: (optional) if ``False``, the response content will be immediately downloaded.43 :param cert: (optional) if String, path to ssl client cert file (.pem). If Tuple, ('cert', 'key') pair.44 :return: :class:`Response <Response>` object45 :rtype: requests.Response4647 Usage::4849 >>> import requests50 >>> req = requests.request('GET', 'https://httpbin.org/get')51 >>> req52 <Response [200]>53 """5455 # By using the 'with' statement we are sure the session is closed, thus we56 # avoid leaving sockets open which can trigger a ResourceWarning in some57 # cases, and look like a memory leak in others.58 with sessions.Session() as session:59 return session.request(method=method, url=url, **kwargs)606162def get(url, params=None, **kwargs):63 r"""Sends a GET request.6465 :param url: URL for the new :class:`Request` object.66 :param params: (optional) Dictionary, list of tuples or bytes to send67 in the query string for the :class:`Request`.68 :param \*\*kwargs: Optional arguments that ``request`` takes.69 :return: :class:`Response <Response>` object70 :rtype: requests.Response71 """7273 return request("get", url, params=params, **kwargs)747576def options(url, **kwargs):77 r"""Sends an OPTIONS request.7879 :param url: URL for the new :class:`Request` object.80 :param \*\*kwargs: Optional arguments that ``request`` takes.81 :return: :class:`Response <Response>` object82 :rtype: requests.Response83 """8485 return request("options", url, **kwargs)868788def head(url, **kwargs):89 r"""Sends a HEAD request.9091 :param url: URL for the new :class:`Request` object.92 :param \*\*kwargs: Optional arguments that ``request`` takes. If93 `allow_redirects` is not provided, it will be set to `False` (as94 opposed to the default :meth:`request` behavior).95 :return: :class:`Response <Response>` object96 :rtype: requests.Response97 """9899 kwargs.setdefault("allow_redirects", False)100 return request("head", url, **kwargs)101102103def post(url, data=None, json=None, **kwargs):104 r"""Sends a POST request.105106 :param url: URL for the new :class:`Request` object.107 :param data: (optional) Dictionary, list of tuples, bytes, or file-like108 object to send in the body of the :class:`Request`.109 :param json: (optional) A JSON serializable Python object to send in the body of the :class:`Request`.110 :param \*\*kwargs: Optional arguments that ``request`` takes.111 :return: :class:`Response <Response>` object112 :rtype: requests.Response113 """114115 return request("post", url, data=data, json=json, **kwargs)116117118def put(url, data=None, **kwargs):119 r"""Sends a PUT request.120121 :param url: URL for the new :class:`Request` object.122 :param data: (optional) Dictionary, list of tuples, bytes, or file-like123 object to send in the body of the :class:`Request`.124 :param json: (optional) A JSON serializable Python object to send in the body of the :class:`Request`.125 :param \*\*kwargs: Optional arguments that ``request`` takes.126 :return: :class:`Response <Response>` object127 :rtype: requests.Response128 """129130 return request("put", url, data=data, **kwargs)131132133def patch(url, data=None, **kwargs):134 r"""Sends a PATCH request.135136 :param url: URL for the new :class:`Request` object.137 :param data: (optional) Dictionary, list of tuples, bytes, or file-like138 object to send in the body of the :class:`Request`.139 :param json: (optional) A JSON serializable Python object to send in the body of the :class:`Request`.140 :param \*\*kwargs: Optional arguments that ``request`` takes.141 :return: :class:`Response <Response>` object142 :rtype: requests.Response143 """144145 return request("patch", url, data=data, **kwargs)146147148def delete(url, **kwargs):149 r"""Sends a DELETE request.150151 :param url: URL for the new :class:`Request` object.152 :param \*\*kwargs: Optional arguments that ``request`` takes.153 :return: :class:`Response <Response>` object154 :rtype: requests.Response155 """156157 return request("delete", url, **kwargs)
added:src/requests/auth.py+314 added
1"""2requests.auth3~~~~~~~~~~~~~45This module contains the authentication handlers for Requests.6"""78import hashlib9import os10import re11import threading12import time13import warnings14from base64 import b64encode1516from ._internal_utils import to_native_string17from .compat import basestring, str, urlparse18from .cookies import extract_cookies_to_jar19from .utils import parse_dict_header2021CONTENT_TYPE_FORM_URLENCODED = "application/x-www-form-urlencoded"22CONTENT_TYPE_MULTI_PART = "multipart/form-data"232425def _basic_auth_str(username, password):26 """Returns a Basic Auth string."""2728 # "I want us to put a big-ol' comment on top of it that29 # says that this behaviour is dumb but we need to preserve30 # it because people are relying on it."31 # - Lukasa32 #33 # These are here solely to maintain backwards compatibility34 # for things like ints. This will be removed in 3.0.0.35 if not isinstance(username, basestring):36 warnings.warn(37 "Non-string usernames will no longer be supported in Requests "38 "3.0.0. Please convert the object you've passed in ({!r}) to "39 "a string or bytes object in the near future to avoid "40 "problems.".format(username),41 category=DeprecationWarning,42 )43 username = str(username)4445 if not isinstance(password, basestring):46 warnings.warn(47 "Non-string passwords will no longer be supported in Requests "48 "3.0.0. Please convert the object you've passed in ({!r}) to "49 "a string or bytes object in the near future to avoid "50 "problems.".format(type(password)),51 category=DeprecationWarning,52 )53 password = str(password)54 # -- End Removal --5556 if isinstance(username, str):57 username = username.encode("latin1")5859 if isinstance(password, str):60 password = password.encode("latin1")6162 authstr = "Basic " + to_native_string(63 b64encode(b":".join((username, password))).strip()64 )6566 return authstr676869class AuthBase:70 """Base class that all auth implementations derive from"""7172 def __call__(self, r):73 raise NotImplementedError("Auth hooks must be callable.")747576class HTTPBasicAuth(AuthBase):77 """Attaches HTTP Basic Authentication to the given Request object."""7879 def __init__(self, username, password):80 self.username = username81 self.password = password8283 def __eq__(self, other):84 return all(85 [86 self.username == getattr(other, "username", None),87 self.password == getattr(other, "password", None),88 ]89 )9091 def __ne__(self, other):92 return not self == other9394 def __call__(self, r):95 r.headers["Authorization"] = _basic_auth_str(self.username, self.password)96 return r979899class HTTPProxyAuth(HTTPBasicAuth):100 """Attaches HTTP Proxy Authentication to a given Request object."""101102 def __call__(self, r):103 r.headers["Proxy-Authorization"] = _basic_auth_str(self.username, self.password)104 return r105106107class HTTPDigestAuth(AuthBase):108 """Attaches HTTP Digest Authentication to the given Request object."""109110 def __init__(self, username, password):111 self.username = username112 self.password = password113 # Keep state in per-thread local storage114 self._thread_local = threading.local()115116 def init_per_thread_state(self):117 # Ensure state is initialized just once per-thread118 if not hasattr(self._thread_local, "init"):119 self._thread_local.init = True120 self._thread_local.last_nonce = ""121 self._thread_local.nonce_count = 0122 self._thread_local.chal = {}123 self._thread_local.pos = None124 self._thread_local.num_401_calls = None125126 def build_digest_header(self, method, url):127 """128 :rtype: str129 """130131 realm = self._thread_local.chal["realm"]132 nonce = self._thread_local.chal["nonce"]133 qop = self._thread_local.chal.get("qop")134 algorithm = self._thread_local.chal.get("algorithm")135 opaque = self._thread_local.chal.get("opaque")136 hash_utf8 = None137138 if algorithm is None:139 _algorithm = "MD5"140 else:141 _algorithm = algorithm.upper()142 # lambdas assume digest modules are imported at the top level143 if _algorithm == "MD5" or _algorithm == "MD5-SESS":144145 def md5_utf8(x):146 if isinstance(x, str):147 x = x.encode("utf-8")148 return hashlib.md5(x).hexdigest()149150 hash_utf8 = md5_utf8151 elif _algorithm == "SHA":152153 def sha_utf8(x):154 if isinstance(x, str):155 x = x.encode("utf-8")156 return hashlib.sha1(x).hexdigest()157158 hash_utf8 = sha_utf8159 elif _algorithm == "SHA-256":160161 def sha256_utf8(x):162 if isinstance(x, str):163 x = x.encode("utf-8")164 return hashlib.sha256(x).hexdigest()165166 hash_utf8 = sha256_utf8167 elif _algorithm == "SHA-512":168169 def sha512_utf8(x):170 if isinstance(x, str):171 x = x.encode("utf-8")172 return hashlib.sha512(x).hexdigest()173174 hash_utf8 = sha512_utf8175176 KD = lambda s, d: hash_utf8(f"{s}:{d}") # noqa:E731177178 if hash_utf8 is None:179 return None180181 # XXX not implemented yet182 entdig = None183 p_parsed = urlparse(url)184 #: path is request-uri defined in RFC 2616 which should not be empty185 path = p_parsed.path or "/"186 if p_parsed.query:187 path += f"?{p_parsed.query}"188189 A1 = f"{self.username}:{realm}:{self.password}"190 A2 = f"{method}:{path}"191192 HA1 = hash_utf8(A1)193 HA2 = hash_utf8(A2)194195 if nonce == self._thread_local.last_nonce:196 self._thread_local.nonce_count += 1197 else:198 self._thread_local.nonce_count = 1199 ncvalue = f"{self._thread_local.nonce_count:08x}"200 s = str(self._thread_local.nonce_count).encode("utf-8")201 s += nonce.encode("utf-8")202 s += time.ctime().encode("utf-8")203 s += os.urandom(8)204205 cnonce = hashlib.sha1(s).hexdigest()[:16]206 if _algorithm == "MD5-SESS":207 HA1 = hash_utf8(f"{HA1}:{nonce}:{cnonce}")208209 if not qop:210 respdig = KD(HA1, f"{nonce}:{HA2}")211 elif qop == "auth" or "auth" in qop.split(","):212 noncebit = f"{nonce}:{ncvalue}:{cnonce}:auth:{HA2}"213 respdig = KD(HA1, noncebit)214 else:215 # XXX handle auth-int.216 return None217218 self._thread_local.last_nonce = nonce219220 # XXX should the partial digests be encoded too?221 base = (222 f'username="{self.username}", realm="{realm}", nonce="{nonce}", '223 f'uri="{path}", response="{respdig}"'224 )225 if opaque:226 base += f', opaque="{opaque}"'227 if algorithm:228 base += f', algorithm="{algorithm}"'229 if entdig:230 base += f', digest="{entdig}"'231 if qop:232 base += f', qop="auth", nc={ncvalue}, cnonce="{cnonce}"'233234 return f"Digest {base}"235236 def handle_redirect(self, r, **kwargs):237 """Reset num_401_calls counter on redirects."""238 if r.is_redirect:239 self._thread_local.num_401_calls = 1240241 def handle_401(self, r, **kwargs):242 """243 Takes the given response and tries digest-auth, if needed.244245 :rtype: requests.Response246 """247248 # If response is not 4xx, do not auth249 # See https://github.com/psf/requests/issues/3772250 if not 400 <= r.status_code < 500:251 self._thread_local.num_401_calls = 1252 return r253254 if self._thread_local.pos is not None:255 # Rewind the file position indicator of the body to where256 # it was to resend the request.257 r.request.body.seek(self._thread_local.pos)258 s_auth = r.headers.get("www-authenticate", "")259260 if "digest" in s_auth.lower() and self._thread_local.num_401_calls < 2:261 self._thread_local.num_401_calls += 1262 pat = re.compile(r"digest ", flags=re.IGNORECASE)263 self._thread_local.chal = parse_dict_header(pat.sub("", s_auth, count=1))264265 # Consume content and release the original connection266 # to allow our new request to reuse the same one.267 r.content268 r.close()269 prep = r.request.copy()270 extract_cookies_to_jar(prep._cookies, r.request, r.raw)271 prep.prepare_cookies(prep._cookies)272273 prep.headers["Authorization"] = self.build_digest_header(274 prep.method, prep.url275 )276 _r = r.connection.send(prep, **kwargs)277 _r.history.append(r)278 _r.request = prep279280 return _r281282 self._thread_local.num_401_calls = 1283 return r284285 def __call__(self, r):286 # Initialize per-thread state, if needed287 self.init_per_thread_state()288 # If we have a saved nonce, skip the 401289 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:294 # In the case of HTTPDigestAuth being reused and the body of295 # the previous request was a file-like object, pos has the296 # file position of the previous body. Ensure it's set to297 # None.298 self._thread_local.pos = None299 r.register_hook("response", self.handle_401)300 r.register_hook("response", self.handle_redirect)301 self._thread_local.num_401_calls = 1302303 return r304305 def __eq__(self, other):306 return all(307 [308 self.username == getattr(other, "username", None),309 self.password == getattr(other, "password", None),310 ]311 )312313 def __ne__(self, other):314 return not self == other
added:src/requests/certs.py+17 added
1#!/usr/bin/env python23"""4requests.certs5~~~~~~~~~~~~~~67This module returns the preferred default CA certificate bundle. There is8only one — the one from the certifi package.910If you are packaging Requests, e.g., for a Linux distribution or a managed11environment, you can change the definition of where() to return a separately12packaged CA bundle.13"""14from certifi import where1516if __name__ == "__main__":17 print(where())
added:src/requests/compat.py+79 added
1"""2requests.compat3~~~~~~~~~~~~~~~45This module previously handled import compatibility issues6between Python 2 and Python 3. It remains for backwards7compatibility until the next major version.8"""910try:11 import chardet12except ImportError:13 import charset_normalizer as chardet1415import sys1617# -------18# Pythons19# -------2021# Syntax sugar.22_ver = sys.version_info2324#: Python 2.x?25is_py2 = _ver[0] == 22627#: Python 3.x?28is_py3 = _ver[0] == 32930# json/simplejson module import resolution31has_simplejson = False32try:33 import simplejson as json3435 has_simplejson = True36except ImportError:37 import json3839if has_simplejson:40 from simplejson import JSONDecodeError41else:42 from json import JSONDecodeError4344# Keep OrderedDict for backwards compatibility.45from collections import OrderedDict46from collections.abc import Callable, Mapping, MutableMapping47from http import cookiejar as cookielib48from http.cookies import Morsel49from io import StringIO5051# --------------52# Legacy Imports53# --------------54from urllib.parse import (55 quote,56 quote_plus,57 unquote,58 unquote_plus,59 urldefrag,60 urlencode,61 urljoin,62 urlparse,63 urlsplit,64 urlunparse,65)66from urllib.request import (67 getproxies,68 getproxies_environment,69 parse_http_list,70 proxy_bypass,71 proxy_bypass_environment,72)7374builtin_str = str75str = str76bytes = bytes77basestring = (str, bytes)78numeric_types = (int, float)79integer_types = (int,)
added:src/requests/cookies.py+561 added
1"""2requests.cookies3~~~~~~~~~~~~~~~~45Compatibility code to be able to use `http.cookiejar.CookieJar` with requests.67requests.utils imports from here, so be careful with imports.8"""910import calendar11import copy12import time1314from ._internal_utils import to_native_string15from .compat import Morsel, MutableMapping, cookielib, urlparse, urlunparse1617try:18 import threading19except ImportError:20 import dummy_threading as threading212223class MockRequest:24 """Wraps a `requests.Request` to mimic a `urllib2.Request`.2526 The code in `http.cookiejar.CookieJar` expects this interface in order to correctly27 manage cookie policies, i.e., determine whether a cookie can be set, given the28 domains of the request and the cookie.2930 The original request object is read-only. The client is responsible for collecting31 the new headers via `get_new_headers()` and interpreting them appropriately. You32 probably want `get_cookie_header`, defined below.33 """3435 def __init__(self, request):36 self._r = request37 self._new_headers = {}38 self.type = urlparse(self._r.url).scheme3940 def get_type(self):41 return self.type4243 def get_host(self):44 return urlparse(self._r.url).netloc4546 def get_origin_req_host(self):47 return self.get_host()4849 def get_full_url(self):50 # Only return the response's URL if the user hadn't set the Host51 # header52 if not self._r.headers.get("Host"):53 return self._r.url54 # If they did set it, retrieve it and reconstruct the expected domain55 host = to_native_string(self._r.headers["Host"], encoding="utf-8")56 parsed = urlparse(self._r.url)57 # Reconstruct the URL as we expect it58 return urlunparse(59 [60 parsed.scheme,61 host,62 parsed.path,63 parsed.params,64 parsed.query,65 parsed.fragment,66 ]67 )6869 def is_unverifiable(self):70 return True7172 def has_header(self, name):73 return name in self._r.headers or name in self._new_headers7475 def get_header(self, name, default=None):76 return self._r.headers.get(name, self._new_headers.get(name, default))7778 def add_header(self, key, val):79 """cookiejar has no legitimate use for this method; add it back if you find one."""80 raise NotImplementedError(81 "Cookie headers should be added with add_unredirected_header()"82 )8384 def add_unredirected_header(self, name, value):85 self._new_headers[name] = value8687 def get_new_headers(self):88 return self._new_headers8990 @property91 def unverifiable(self):92 return self.is_unverifiable()9394 @property95 def origin_req_host(self):96 return self.get_origin_req_host()9798 @property99 def host(self):100 return self.get_host()101102103class MockResponse:104 """Wraps a `httplib.HTTPMessage` to mimic a `urllib.addinfourl`.105106 ...what? Basically, expose the parsed HTTP headers from the server response107 the way `http.cookiejar` expects to see them.108 """109110 def __init__(self, headers):111 """Make a MockResponse for `cookiejar` to read.112113 :param headers: a httplib.HTTPMessage or analogous carrying the headers114 """115 self._headers = headers116117 def info(self):118 return self._headers119120 def getheaders(self, name):121 self._headers.getheaders(name)122123124def extract_cookies_to_jar(jar, request, response):125 """Extract the cookies from the response into a CookieJar.126127 :param jar: http.cookiejar.CookieJar (not necessarily a RequestsCookieJar)128 :param request: our own requests.Request object129 :param response: urllib3.HTTPResponse object130 """131 if not (hasattr(response, "_original_response") and response._original_response):132 return133 # the _original_response field is the wrapped httplib.HTTPResponse object,134 req = MockRequest(request)135 # pull out the HTTPMessage with the headers and put it in the mock:136 res = MockResponse(response._original_response.msg)137 jar.extract_cookies(res, req)138139140def get_cookie_header(jar, request):141 """142 Produce an appropriate Cookie header string to be sent with `request`, or None.143144 :rtype: str145 """146 r = MockRequest(request)147 jar.add_cookie_header(r)148 return r.get_new_headers().get("Cookie")149150151def remove_cookie_by_name(cookiejar, name, domain=None, path=None):152 """Unsets a cookie by name, by default over all domains and paths.153154 Wraps CookieJar.clear(), is O(n).155 """156 clearables = []157 for cookie in cookiejar:158 if cookie.name != name:159 continue160 if domain is not None and domain != cookie.domain:161 continue162 if path is not None and path != cookie.path:163 continue164 clearables.append((cookie.domain, cookie.path, cookie.name))165166 for domain, path, name in clearables:167 cookiejar.clear(domain, path, name)168169170class CookieConflictError(RuntimeError):171 """There are two cookies that meet the criteria specified in the cookie jar.172 Use .get and .set and include domain and path args in order to be more specific.173 """174175176class RequestsCookieJar(cookielib.CookieJar, MutableMapping):177 """Compatibility class; is a http.cookiejar.CookieJar, but exposes a dict178 interface.179180 This is the CookieJar we create by default for requests and sessions that181 don't specify one, since some clients may expect response.cookies and182 session.cookies to support dict operations.183184 Requests does not use the dict interface internally; it's just for185 compatibility with external client code. All requests code should work186 out of the box with externally provided instances of ``CookieJar``, e.g.187 ``LWPCookieJar`` and ``FileCookieJar``.188189 Unlike a regular CookieJar, this class is pickleable.190191 .. warning:: dictionary operations that are normally O(1) may be O(n).192 """193194 def get(self, name, default=None, domain=None, path=None):195 """Dict-like get() that also supports optional domain and path args in196 order to resolve naming collisions from using one cookie jar over197 multiple domains.198199 .. warning:: operation is O(n), not O(1).200 """201 try:202 return self._find_no_duplicates(name, domain, path)203 except KeyError:204 return default205206 def set(self, name, value, **kwargs):207 """Dict-like set() that also supports optional domain and path args in208 order to resolve naming collisions from using one cookie jar over209 multiple domains.210 """211 # support client code that unsets cookies by assignment of a None value:212 if value is None:213 remove_cookie_by_name(214 self, name, domain=kwargs.get("domain"), path=kwargs.get("path")215 )216 return217218 if isinstance(value, Morsel):219 c = morsel_to_cookie(value)220 else:221 c = create_cookie(name, value, **kwargs)222 self.set_cookie(c)223 return c224225 def iterkeys(self):226 """Dict-like iterkeys() that returns an iterator of names of cookies227 from the jar.228229 .. seealso:: itervalues() and iteritems().230 """231 for cookie in iter(self):232 yield cookie.name233234 def keys(self):235 """Dict-like keys() that returns a list of names of cookies from the236 jar.237238 .. seealso:: values() and items().239 """240 return list(self.iterkeys())241242 def itervalues(self):243 """Dict-like itervalues() that returns an iterator of values of cookies244 from the jar.245246 .. seealso:: iterkeys() and iteritems().247 """248 for cookie in iter(self):249 yield cookie.value250251 def values(self):252 """Dict-like values() that returns a list of values of cookies from the253 jar.254255 .. seealso:: keys() and items().256 """257 return list(self.itervalues())258259 def iteritems(self):260 """Dict-like iteritems() that returns an iterator of name-value tuples261 from the jar.262263 .. seealso:: iterkeys() and itervalues().264 """265 for cookie in iter(self):266 yield cookie.name, cookie.value267268 def items(self):269 """Dict-like items() that returns a list of name-value tuples from the270 jar. Allows client-code to call ``dict(RequestsCookieJar)`` and get a271 vanilla python dict of key value pairs.272273 .. seealso:: keys() and values().274 """275 return list(self.iteritems())276277 def list_domains(self):278 """Utility method to list all the domains in the jar."""279 domains = []280 for cookie in iter(self):281 if cookie.domain not in domains:282 domains.append(cookie.domain)283 return domains284285 def list_paths(self):286 """Utility method to list all the paths in the jar."""287 paths = []288 for cookie in iter(self):289 if cookie.path not in paths:290 paths.append(cookie.path)291 return paths292293 def multiple_domains(self):294 """Returns True if there are multiple domains in the jar.295 Returns False otherwise.296297 :rtype: bool298 """299 domains = []300 for cookie in iter(self):301 if cookie.domain is not None and cookie.domain in domains:302 return True303 domains.append(cookie.domain)304 return False # there is only one domain in jar305306 def get_dict(self, domain=None, path=None):307 """Takes as an argument an optional domain and path and returns a plain308 old Python dict of name-value pairs of cookies that meet the309 requirements.310311 :rtype: dict312 """313 dictionary = {}314 for cookie in iter(self):315 if (domain is None or cookie.domain == domain) and (316 path is None or cookie.path == path317 ):318 dictionary[cookie.name] = cookie.value319 return dictionary320321 def __contains__(self, name):322 try:323 return super().__contains__(name)324 except CookieConflictError:325 return True326327 def __getitem__(self, name):328 """Dict-like __getitem__() for compatibility with client code. Throws329 exception if there are more than one cookie with name. In that case,330 use the more explicit get() method instead.331332 .. warning:: operation is O(n), not O(1).333 """334 return self._find_no_duplicates(name)335336 def __setitem__(self, name, value):337 """Dict-like __setitem__ for compatibility with client code. Throws338 exception if there is already a cookie of that name in the jar. In that339 case, use the more explicit set() method instead.340 """341 self.set(name, value)342343 def __delitem__(self, name):344 """Deletes a cookie given a name. Wraps ``http.cookiejar.CookieJar``'s345 ``remove_cookie_by_name()``.346 """347 remove_cookie_by_name(self, name)348349 def set_cookie(self, cookie, *args, **kwargs):350 if (351 hasattr(cookie.value, "startswith")352 and cookie.value.startswith('"')353 and cookie.value.endswith('"')354 ):355 cookie.value = cookie.value.replace('\\"', "")356 return super().set_cookie(cookie, *args, **kwargs)357358 def update(self, other):359 """Updates this jar with cookies from another CookieJar or dict-like"""360 if isinstance(other, cookielib.CookieJar):361 for cookie in other:362 self.set_cookie(copy.copy(cookie))363 else:364 super().update(other)365366 def _find(self, name, domain=None, path=None):367 """Requests uses this method internally to get cookie values.368369 If there are conflicting cookies, _find arbitrarily chooses one.370 See _find_no_duplicates if you want an exception thrown if there are371 conflicting cookies.372373 :param name: a string containing name of cookie374 :param domain: (optional) string containing domain of cookie375 :param path: (optional) string containing path of cookie376 :return: cookie.value377 """378 for cookie in iter(self):379 if cookie.name == name:380 if domain is None or cookie.domain == domain:381 if path is None or cookie.path == path:382 return cookie.value383384 raise KeyError(f"name={name!r}, domain={domain!r}, path={path!r}")385386 def _find_no_duplicates(self, name, domain=None, path=None):387 """Both ``__get_item__`` and ``get`` call this function: it's never388 used elsewhere in Requests.389390 :param name: a string containing name of cookie391 :param domain: (optional) string containing domain of cookie392 :param path: (optional) string containing path of cookie393 :raises KeyError: if cookie is not found394 :raises CookieConflictError: if there are multiple cookies395 that match name and optionally domain and path396 :return: cookie.value397 """398 toReturn = None399 for cookie in iter(self):400 if cookie.name == name:401 if domain is None or cookie.domain == domain:402 if path is None or cookie.path == path:403 if toReturn is not None:404 # if there are multiple cookies that meet passed in criteria405 raise CookieConflictError(406 f"There are multiple cookies with name, {name!r}"407 )408 # we will eventually return this as long as no cookie conflict409 toReturn = cookie.value410411 if toReturn:412 return toReturn413 raise KeyError(f"name={name!r}, domain={domain!r}, path={path!r}")414415 def __getstate__(self):416 """Unlike a normal CookieJar, this class is pickleable."""417 state = self.__dict__.copy()418 # remove the unpickleable RLock object419 state.pop("_cookies_lock")420 return state421422 def __setstate__(self, state):423 """Unlike a normal CookieJar, this class is pickleable."""424 self.__dict__.update(state)425 if "_cookies_lock" not in self.__dict__:426 self._cookies_lock = threading.RLock()427428 def copy(self):429 """Return a copy of this RequestsCookieJar."""430 new_cj = RequestsCookieJar()431 new_cj.set_policy(self.get_policy())432 new_cj.update(self)433 return new_cj434435 def get_policy(self):436 """Return the CookiePolicy instance used."""437 return self._policy438439440def _copy_cookie_jar(jar):441 if jar is None:442 return None443444 if hasattr(jar, "copy"):445 # We're dealing with an instance of RequestsCookieJar446 return jar.copy()447 # We're dealing with a generic CookieJar instance448 new_jar = copy.copy(jar)449 new_jar.clear()450 for cookie in jar:451 new_jar.set_cookie(copy.copy(cookie))452 return new_jar453454455def create_cookie(name, value, **kwargs):456 """Make a cookie from underspecified parameters.457458 By default, the pair of `name` and `value` will be set for the domain ''459 and sent on every request (this is sometimes called a "supercookie").460 """461 result = {462 "version": 0,463 "name": name,464 "value": value,465 "port": None,466 "domain": "",467 "path": "/",468 "secure": False,469 "expires": None,470 "discard": True,471 "comment": None,472 "comment_url": None,473 "rest": {"HttpOnly": None},474 "rfc2109": False,475 }476477 badargs = set(kwargs) - set(result)478 if badargs:479 raise TypeError(480 f"create_cookie() got unexpected keyword arguments: {list(badargs)}"481 )482483 result.update(kwargs)484 result["port_specified"] = bool(result["port"])485 result["domain_specified"] = bool(result["domain"])486 result["domain_initial_dot"] = result["domain"].startswith(".")487 result["path_specified"] = bool(result["path"])488489 return cookielib.Cookie(**result)490491492def morsel_to_cookie(morsel):493 """Convert a Morsel object into a Cookie containing the one k/v pair."""494495 expires = None496 if morsel["max-age"]:497 try:498 expires = int(time.time() + int(morsel["max-age"]))499 except ValueError:500 raise TypeError(f"max-age: {morsel['max-age']} must be integer")501 elif morsel["expires"]:502 time_template = "%a, %d-%b-%Y %H:%M:%S GMT"503 expires = calendar.timegm(time.strptime(morsel["expires"], time_template))504 return create_cookie(505 comment=morsel["comment"],506 comment_url=bool(morsel["comment"]),507 discard=False,508 domain=morsel["domain"],509 expires=expires,510 name=morsel.key,511 path=morsel["path"],512 port=None,513 rest={"HttpOnly": morsel["httponly"]},514 rfc2109=False,515 secure=bool(morsel["secure"]),516 value=morsel.value,517 version=morsel["version"] or 0,518 )519520521def cookiejar_from_dict(cookie_dict, cookiejar=None, overwrite=True):522 """Returns a CookieJar from a key/value dictionary.523524 :param cookie_dict: Dict of key/values to insert into CookieJar.525 :param cookiejar: (optional) A cookiejar to add the cookies to.526 :param overwrite: (optional) If False, will not replace cookies527 already in the jar with new ones.528 :rtype: CookieJar529 """530 if cookiejar is None:531 cookiejar = RequestsCookieJar()532533 if cookie_dict is not None:534 names_from_jar = [cookie.name for cookie in cookiejar]535 for name in cookie_dict:536 if overwrite or (name not in names_from_jar):537 cookiejar.set_cookie(create_cookie(name, cookie_dict[name]))538539 return cookiejar540541542def merge_cookies(cookiejar, cookies):543 """Add cookies to cookiejar and returns a merged CookieJar.544545 :param cookiejar: CookieJar object to add the cookies to.546 :param cookies: Dictionary or CookieJar object to be added.547 :rtype: CookieJar548 """549 if not isinstance(cookiejar, cookielib.CookieJar):550 raise ValueError("You can only merge into CookieJar")551552 if isinstance(cookies, dict):553 cookiejar = cookiejar_from_dict(cookies, cookiejar=cookiejar, overwrite=False)554 elif isinstance(cookies, cookielib.CookieJar):555 try:556 cookiejar.update(cookies)557 except AttributeError:558 for cookie_in_jar in cookies:559 cookiejar.set_cookie(cookie_in_jar)560561 return cookiejar
added:src/requests/exceptions.py+141 added
1"""2requests.exceptions3~~~~~~~~~~~~~~~~~~~45This module contains the set of Requests' exceptions.6"""7from urllib3.exceptions import HTTPError as BaseHTTPError89from .compat import JSONDecodeError as CompatJSONDecodeError101112class RequestException(IOError):13 """There was an ambiguous exception that occurred while handling your14 request.15 """1617 def __init__(self, *args, **kwargs):18 """Initialize RequestException with `request` and `response` objects."""19 response = kwargs.pop("response", None)20 self.response = response21 self.request = kwargs.pop("request", None)22 if response is not None and not self.request and hasattr(response, "request"):23 self.request = self.response.request24 super().__init__(*args, **kwargs)252627class InvalidJSONError(RequestException):28 """A JSON error occurred."""293031class JSONDecodeError(InvalidJSONError, CompatJSONDecodeError):32 """Couldn't decode the text into json"""3334 def __init__(self, *args, **kwargs):35 """36 Construct the JSONDecodeError instance first with all37 args. Then use it's args to construct the IOError so that38 the json specific args aren't used as IOError specific args39 and the error message from JSONDecodeError is preserved.40 """41 CompatJSONDecodeError.__init__(self, *args)42 InvalidJSONError.__init__(self, *self.args, **kwargs)434445class HTTPError(RequestException):46 """An HTTP error occurred."""474849class ConnectionError(RequestException):50 """A Connection error occurred."""515253class ProxyError(ConnectionError):54 """A proxy error occurred."""555657class SSLError(ConnectionError):58 """An SSL error occurred."""596061class Timeout(RequestException):62 """The request timed out.6364 Catching this error will catch both65 :exc:`~requests.exceptions.ConnectTimeout` and66 :exc:`~requests.exceptions.ReadTimeout` errors.67 """686970class ConnectTimeout(ConnectionError, Timeout):71 """The request timed out while trying to connect to the remote server.7273 Requests that produced this error are safe to retry.74 """757677class ReadTimeout(Timeout):78 """The server did not send any data in the allotted amount of time."""798081class URLRequired(RequestException):82 """A valid URL is required to make a request."""838485class TooManyRedirects(RequestException):86 """Too many redirects."""878889class MissingSchema(RequestException, ValueError):90 """The URL scheme (e.g. http or https) is missing."""919293class InvalidSchema(RequestException, ValueError):94 """The URL scheme provided is either invalid or unsupported."""959697class InvalidURL(RequestException, ValueError):98 """The URL provided was somehow invalid."""99100101class InvalidHeader(RequestException, ValueError):102 """The header value provided was somehow invalid."""103104105class InvalidProxyURL(InvalidURL):106 """The proxy URL provided is invalid."""107108109class ChunkedEncodingError(RequestException):110 """The server declared chunked encoding but sent an invalid chunk."""111112113class ContentDecodingError(RequestException, BaseHTTPError):114 """Failed to decode response content."""115116117class StreamConsumedError(RequestException, TypeError):118 """The content for this response was already consumed."""119120121class RetryError(RequestException):122 """Custom retries logic failed"""123124125class UnrewindableBodyError(RequestException):126 """Requests encountered an error when trying to rewind a body."""127128129# Warnings130131132class RequestsWarning(Warning):133 """Base warning for Requests."""134135136class FileModeWarning(RequestsWarning, DeprecationWarning):137 """A file was opened in text mode, but Requests determined its binary length."""138139140class RequestsDependencyWarning(RequestsWarning):141 """An imported dependency doesn't match the expected version range."""
added:src/requests/help.py+134 added
1"""Module containing bug report helper(s)."""23import json4import platform5import ssl6import sys78import idna9import urllib31011from . import __version__ as requests_version1213try:14 import charset_normalizer15except ImportError:16 charset_normalizer = None1718try:19 import chardet20except ImportError:21 chardet = None2223try:24 from urllib3.contrib import pyopenssl25except ImportError:26 pyopenssl = None27 OpenSSL = None28 cryptography = None29else:30 import cryptography31 import OpenSSL323334def _implementation():35 """Return a dict with the Python implementation and version.3637 Provide both the name and the version of the Python implementation38 currently running. For example, on CPython 3.10.3 it will return39 {'name': 'CPython', 'version': '3.10.3'}.4041 This function works best on CPython and PyPy: in particular, it probably42 doesn't work for Jython or IronPython. Future investigation should be done43 to work out the correct shape of the code for those platforms.44 """45 implementation = platform.python_implementation()4647 if implementation == "CPython":48 implementation_version = platform.python_version()49 elif implementation == "PyPy":50 implementation_version = "{}.{}.{}".format(51 sys.pypy_version_info.major,52 sys.pypy_version_info.minor,53 sys.pypy_version_info.micro,54 )55 if sys.pypy_version_info.releaselevel != "final":56 implementation_version = "".join(57 [implementation_version, sys.pypy_version_info.releaselevel]58 )59 elif implementation == "Jython":60 implementation_version = platform.python_version() # Complete Guess61 elif implementation == "IronPython":62 implementation_version = platform.python_version() # Complete Guess63 else:64 implementation_version = "Unknown"6566 return {"name": implementation, "version": implementation_version}676869def info():70 """Generate information for a bug report."""71 try:72 platform_info = {73 "system": platform.system(),74 "release": platform.release(),75 }76 except OSError:77 platform_info = {78 "system": "Unknown",79 "release": "Unknown",80 }8182 implementation_info = _implementation()83 urllib3_info = {"version": urllib3.__version__}84 charset_normalizer_info = {"version": None}85 chardet_info = {"version": None}86 if charset_normalizer:87 charset_normalizer_info = {"version": charset_normalizer.__version__}88 if chardet:89 chardet_info = {"version": chardet.__version__}9091 pyopenssl_info = {92 "version": None,93 "openssl_version": "",94 }95 if OpenSSL:96 pyopenssl_info = {97 "version": OpenSSL.__version__,98 "openssl_version": f"{OpenSSL.SSL.OPENSSL_VERSION_NUMBER:x}",99 }100 cryptography_info = {101 "version": getattr(cryptography, "__version__", ""),102 }103 idna_info = {104 "version": getattr(idna, "__version__", ""),105 }106107 system_ssl = ssl.OPENSSL_VERSION_NUMBER108 system_ssl_info = {"version": f"{system_ssl:x}" if system_ssl is not None else ""}109110 return {111 "platform": platform_info,112 "implementation": implementation_info,113 "system_ssl": system_ssl_info,114 "using_pyopenssl": pyopenssl is not None,115 "using_charset_normalizer": chardet is None,116 "pyOpenSSL": pyopenssl_info,117 "urllib3": urllib3_info,118 "chardet": chardet_info,119 "charset_normalizer": charset_normalizer_info,120 "cryptography": cryptography_info,121 "idna": idna_info,122 "requests": {123 "version": requests_version,124 },125 }126127128def main():129 """Pretty-print the bug information as JSON."""130 print(json.dumps(info(), sort_keys=True, indent=2))131132133if __name__ == "__main__":134 main()
added:src/requests/hooks.py+33 added
1"""2requests.hooks3~~~~~~~~~~~~~~45This module provides the capabilities for the Requests hooks system.67Available hooks:89``response``:10 The response generated from a Request.11"""12HOOKS = ["response"]131415def default_hooks():16 return {event: [] for event in HOOKS}171819# TODO: response is the only one202122def dispatch_hook(key, hooks, hook_data, **kwargs):23 """Dispatches a hook dictionary on a given piece of data."""24 hooks = hooks or {}25 hooks = hooks.get(key)26 if hooks:27 if hasattr(hooks, "__call__"):28 hooks = [hooks]29 for hook in hooks:30 _hook_data = hook(hook_data, **kwargs)31 if _hook_data is not None:32 hook_data = _hook_data33 return hook_data
added:src/requests/models.py+1032 added
1"""2requests.models3~~~~~~~~~~~~~~~45This module contains the primary objects that power Requests.6"""78import datetime910# Import encoding now, to avoid implicit import later.11# Implicit import within threads may cause LookupError when standard library is in a ZIP,12# such as in Embedded Python. See https://github.com/psf/requests/issues/3578.13import encodings.idna # noqa: F40114from io import UnsupportedOperation1516from urllib3.exceptions import (17 DecodeError,18 LocationParseError,19 ProtocolError,20 ReadTimeoutError,21 SSLError,22)23from urllib3.fields import RequestField24from urllib3.filepost import encode_multipart_formdata25from urllib3.util import parse_url2627from ._internal_utils import to_native_string, unicode_is_ascii28from .auth import HTTPBasicAuth29from .compat import (30 Callable,31 JSONDecodeError,32 Mapping,33 basestring,34 builtin_str,35 chardet,36 cookielib,37)38from .compat import json as complexjson39from .compat import urlencode, urlsplit, urlunparse40from .cookies import _copy_cookie_jar, cookiejar_from_dict, get_cookie_header41from .exceptions import (42 ChunkedEncodingError,43 ConnectionError,44 ContentDecodingError,45 HTTPError,46 InvalidJSONError,47 InvalidURL,48)49from .exceptions import JSONDecodeError as RequestsJSONDecodeError50from .exceptions import MissingSchema51from .exceptions import SSLError as RequestsSSLError52from .exceptions import StreamConsumedError53from .hooks import default_hooks54from .status_codes import codes55from .structures import CaseInsensitiveDict56from .utils import (57 check_header_validity,58 get_auth_from_url,59 guess_filename,60 guess_json_utf,61 iter_slices,62 parse_header_links,63 requote_uri,64 stream_decode_response_unicode,65 super_len,66 to_key_val_list,67)6869#: The set of HTTP status codes that indicate an automatically70#: processable redirect.71REDIRECT_STATI = (72 codes.moved, # 30173 codes.found, # 30274 codes.other, # 30375 codes.temporary_redirect, # 30776 codes.permanent_redirect, # 30877)7879DEFAULT_REDIRECT_LIMIT = 3080CONTENT_CHUNK_SIZE = 10 * 102481ITER_CHUNK_SIZE = 512828384class RequestEncodingMixin:85 @property86 def path_url(self):87 """Build the path URL to use."""8889 url = []9091 p = urlsplit(self.url)9293 path = p.path94 if not path:95 path = "/"9697 url.append(path)9899 query = p.query100 if query:101 url.append("?")102 url.append(query)103104 return "".join(url)105106 @staticmethod107 def _encode_params(data):108 """Encode parameters in a piece of data.109110 Will successfully encode parameters when passed as a dict or a list of111 2-tuples. Order is retained if data is a list of 2-tuples but arbitrary112 if parameters are supplied as a dict.113 """114115 if isinstance(data, (str, bytes)):116 return data117 elif hasattr(data, "read"):118 return data119 elif hasattr(data, "__iter__"):120 result = []121 for k, vs in to_key_val_list(data):122 if isinstance(vs, basestring) or not hasattr(vs, "__iter__"):123 vs = [vs]124 for v in vs:125 if v is not None:126 result.append(127 (128 k.encode("utf-8") if isinstance(k, str) else k,129 v.encode("utf-8") if isinstance(v, str) else v,130 )131 )132 return urlencode(result, doseq=True)133 else:134 return data135136 @staticmethod137 def _encode_files(files, data):138 """Build the body for a multipart/form-data request.139140 Will successfully encode files when passed as a dict or a list of141 tuples. Order is retained if data is a list of tuples but arbitrary142 if parameters are supplied as a dict.143 The tuples may be 2-tuples (filename, fileobj), 3-tuples (filename, fileobj, contentype)144 or 4-tuples (filename, fileobj, contentype, custom_headers).145 """146 if not files:147 raise ValueError("Files must be provided.")148 elif isinstance(data, basestring):149 raise ValueError("Data must not be a string.")150151 new_fields = []152 fields = to_key_val_list(data or {})153 files = to_key_val_list(files or {})154155 for field, val in fields:156 if isinstance(val, basestring) or not hasattr(val, "__iter__"):157 val = [val]158 for v in val:159 if v is not None:160 # Don't call str() on bytestrings: in Py3 it all goes wrong.161 if not isinstance(v, bytes):162 v = str(v)163164 new_fields.append(165 (166 field.decode("utf-8")167 if isinstance(field, bytes)168 else field,169 v.encode("utf-8") if isinstance(v, str) else v,170 )171 )172173 for k, v in files:174 # support for explicit filename175 ft = None176 fh = None177 if isinstance(v, (tuple, list)):178 if len(v) == 2:179 fn, fp = v180 elif len(v) == 3:181 fn, fp, ft = v182 else:183 fn, fp, ft, fh = v184 else:185 fn = guess_filename(v) or k186 fp = v187188 if isinstance(fp, (str, bytes, bytearray)):189 fdata = fp190 elif hasattr(fp, "read"):191 fdata = fp.read()192 elif fp is None:193 continue194 else:195 fdata = fp196197 rf = RequestField(name=k, data=fdata, filename=fn, headers=fh)198 rf.make_multipart(content_type=ft)199 new_fields.append(rf)200201 body, content_type = encode_multipart_formdata(new_fields)202203 return body, content_type204205206class RequestHooksMixin:207 def register_hook(self, event, hook):208 """Properly register a hook."""209210 if event not in self.hooks:211 raise ValueError(f'Unsupported event specified, with event name "{event}"')212213 if isinstance(hook, Callable):214 self.hooks[event].append(hook)215 elif hasattr(hook, "__iter__"):216 self.hooks[event].extend(h for h in hook if isinstance(h, Callable))217218 def deregister_hook(self, event, hook):219 """Deregister a previously registered hook.220 Returns True if the hook existed, False if not.221 """222223 try:224 self.hooks[event].remove(hook)225 return True226 except ValueError:227 return False228229230class Request(RequestHooksMixin):231 """A user-created :class:`Request <Request>` object.232233 Used to prepare a :class:`PreparedRequest <PreparedRequest>`, which is sent to the server.234235 :param method: HTTP method to use.236 :param url: URL to send.237 :param headers: dictionary of headers to send.238 :param files: dictionary of {filename: fileobject} files to multipart upload.239 :param data: the body to attach to the request. If a dictionary or240 list of tuples ``[(key, value)]`` is provided, form-encoding will241 take place.242 :param json: json for the body to attach to the request (if files or data is not specified).243 :param params: URL parameters to append to the URL. If a dictionary or244 list of tuples ``[(key, value)]`` is provided, form-encoding will245 take place.246 :param auth: Auth handler or (user, pass) tuple.247 :param cookies: dictionary or CookieJar of cookies to attach to this request.248 :param hooks: dictionary of callback hooks, for internal usage.249250 Usage::251252 >>> import requests253 >>> req = requests.Request('GET', 'https://httpbin.org/get')254 >>> req.prepare()255 <PreparedRequest [GET]>256 """257258 def __init__(259 self,260 method=None,261 url=None,262 headers=None,263 files=None,264 data=None,265 params=None,266 auth=None,267 cookies=None,268 hooks=None,269 json=None,270 ):271 # Default empty dicts for dict params.272 data = [] if data is None else data273 files = [] if files is None else files274 headers = {} if headers is None else headers275 params = {} if params is None else params276 hooks = {} if hooks is None else hooks277278 self.hooks = default_hooks()279 for k, v in list(hooks.items()):280 self.register_hook(event=k, hook=v)281282 self.method = method283 self.url = url284 self.headers = headers285 self.files = files286 self.data = data287 self.json = json288 self.params = params289 self.auth = auth290 self.cookies = cookies291292 def __repr__(self):293 return f"<Request [{self.method}]>"294295 def prepare(self):296 """Constructs a :class:`PreparedRequest <PreparedRequest>` for transmission and returns it."""297 p = PreparedRequest()298 p.prepare(299 method=self.method,300 url=self.url,301 headers=self.headers,302 files=self.files,303 data=self.data,304 json=self.json,305 params=self.params,306 auth=self.auth,307 cookies=self.cookies,308 hooks=self.hooks,309 )310 return p311312313class PreparedRequest(RequestEncodingMixin, RequestHooksMixin):314 """The fully mutable :class:`PreparedRequest <PreparedRequest>` object,315 containing the exact bytes that will be sent to the server.316317 Instances are generated from a :class:`Request <Request>` object, and318 should not be instantiated manually; doing so may produce undesirable319 effects.320321 Usage::322323 >>> import requests324 >>> req = requests.Request('GET', 'https://httpbin.org/get')325 >>> r = req.prepare()326 >>> r327 <PreparedRequest [GET]>328329 >>> s = requests.Session()330 >>> s.send(r)331 <Response [200]>332 """333334 def __init__(self):335 #: HTTP verb to send to the server.336 self.method = None337 #: HTTP URL to send the request to.338 self.url = None339 #: dictionary of HTTP headers.340 self.headers = None341 # The `CookieJar` used to create the Cookie header will be stored here342 # after prepare_cookies is called343 self._cookies = None344 #: request body to send to the server.345 self.body = None346 #: dictionary of callback hooks, for internal usage.347 self.hooks = default_hooks()348 #: integer denoting starting position of a readable file-like body.349 self._body_position = None350351 def prepare(352 self,353 method=None,354 url=None,355 headers=None,356 files=None,357 data=None,358 params=None,359 auth=None,360 cookies=None,361 hooks=None,362 json=None,363 ):364 """Prepares the entire request with the given parameters."""365366 self.prepare_method(method)367 self.prepare_url(url, params)368 self.prepare_headers(headers)369 self.prepare_cookies(cookies)370 self.prepare_body(data, files, json)371 self.prepare_auth(auth, url)372373 # Note that prepare_auth must be last to enable authentication schemes374 # such as OAuth to work on a fully prepared request.375376 # This MUST go after prepare_auth. Authenticators could add a hook377 self.prepare_hooks(hooks)378379 def __repr__(self):380 return f"<PreparedRequest [{self.method}]>"381382 def copy(self):383 p = PreparedRequest()384 p.method = self.method385 p.url = self.url386 p.headers = self.headers.copy() if self.headers is not None else None387 p._cookies = _copy_cookie_jar(self._cookies)388 p.body = self.body389 p.hooks = self.hooks390 p._body_position = self._body_position391 return p392393 def prepare_method(self, method):394 """Prepares the given HTTP method."""395 self.method = method396 if self.method is not None:397 self.method = to_native_string(self.method.upper())398399 @staticmethod400 def _get_idna_encoded_host(host):401 import idna402403 try:404 host = idna.encode(host, uts46=True).decode("utf-8")405 except idna.IDNAError:406 raise UnicodeError407 return host408409 def prepare_url(self, url, params):410 """Prepares the given HTTP URL."""411 #: Accept objects that have string representations.412 #: We're unable to blindly call unicode/str functions413 #: as this will include the bytestring indicator (b'')414 #: on python 3.x.415 #: https://github.com/psf/requests/pull/2238416 if isinstance(url, bytes):417 url = url.decode("utf8")418 else:419 url = str(url)420421 # Remove leading whitespaces from url422 url = url.lstrip()423424 # Don't do any URL preparation for non-HTTP schemes like `mailto`,425 # `data` etc to work around exceptions from `url_parse`, which426 # handles RFC 3986 only.427 if ":" in url and not url.lower().startswith("http"):428 self.url = url429 return430431 # Support for unicode domain names and paths.432 try:433 scheme, auth, host, port, path, query, fragment = parse_url(url)434 except LocationParseError as e:435 raise InvalidURL(*e.args)436437 if not scheme:438 raise MissingSchema(439 f"Invalid URL {url!r}: No scheme supplied. "440 f"Perhaps you meant https://{url}?"441 )442443 if not host:444 raise InvalidURL(f"Invalid URL {url!r}: No host supplied")445446 # In general, we want to try IDNA encoding the hostname if the string contains447 # non-ASCII characters. This allows users to automatically get the correct IDNA448 # behaviour. For strings containing only ASCII characters, we need to also verify449 # it doesn't start with a wildcard (*), before allowing the unencoded hostname.450 if not unicode_is_ascii(host):451 try:452 host = self._get_idna_encoded_host(host)453 except UnicodeError:454 raise InvalidURL("URL has an invalid label.")455 elif host.startswith(("*", ".")):456 raise InvalidURL("URL has an invalid label.")457458 # Carefully reconstruct the network location459 netloc = auth or ""460 if netloc:461 netloc += "@"462 netloc += host463 if port:464 netloc += f":{port}"465466 # Bare domains aren't valid URLs.467 if not path:468 path = "/"469470 if isinstance(params, (str, bytes)):471 params = to_native_string(params)472473 enc_params = self._encode_params(params)474 if enc_params:475 if query:476 query = f"{query}&{enc_params}"477 else:478 query = enc_params479480 url = requote_uri(urlunparse([scheme, netloc, path, None, query, fragment]))481 self.url = url482483 def prepare_headers(self, headers):484 """Prepares the given HTTP headers."""485486 self.headers = CaseInsensitiveDict()487 if headers:488 for header in headers.items():489 # Raise exception on invalid header value.490 check_header_validity(header)491 name, value = header492 self.headers[to_native_string(name)] = value493494 def prepare_body(self, data, files, json=None):495 """Prepares the given HTTP body data."""496497 # Check if file, fo, generator, iterator.498 # If not, run through normal process.499500 # Nottin' on you.501 body = None502 content_type = None503504 if not data and json is not None:505 # urllib3 requires a bytes-like body. Python 2's json.dumps506 # provides this natively, but Python 3 gives a Unicode string.507 content_type = "application/json"508509 try:510 body = complexjson.dumps(json, allow_nan=False)511 except ValueError as ve:512 raise InvalidJSONError(ve, request=self)513514 if not isinstance(body, bytes):515 body = body.encode("utf-8")516517 is_stream = all(518 [519 hasattr(data, "__iter__"),520 not isinstance(data, (basestring, list, tuple, Mapping)),521 ]522 )523524 if is_stream:525 try:526 length = super_len(data)527 except (TypeError, AttributeError, UnsupportedOperation):528 length = None529530 body = data531532 if getattr(body, "tell", None) is not None:533 # Record the current file position before reading.534 # This will allow us to rewind a file in the event535 # of a redirect.536 try:537 self._body_position = body.tell()538 except OSError:539 # This differentiates from None, allowing us to catch540 # a failed `tell()` later when trying to rewind the body541 self._body_position = object()542543 if files:544 raise NotImplementedError(545 "Streamed bodies and files are mutually exclusive."546 )547548 if length:549 self.headers["Content-Length"] = builtin_str(length)550 else:551 self.headers["Transfer-Encoding"] = "chunked"552 else:553 # Multi-part file uploads.554 if files:555 (body, content_type) = self._encode_files(files, data)556 else:557 if data:558 body = self._encode_params(data)559 if isinstance(data, basestring) or hasattr(data, "read"):560 content_type = None561 else:562 content_type = "application/x-www-form-urlencoded"563564 self.prepare_content_length(body)565566 # Add content-type if it wasn't explicitly provided.567 if content_type and ("content-type" not in self.headers):568 self.headers["Content-Type"] = content_type569570 self.body = body571572 def prepare_content_length(self, body):573 """Prepare Content-Length header based on request method and body"""574 if body is not None:575 length = super_len(body)576 if length:577 # If length exists, set it. Otherwise, we fallback578 # to Transfer-Encoding: chunked.579 self.headers["Content-Length"] = builtin_str(length)580 elif (581 self.method not in ("GET", "HEAD")582 and self.headers.get("Content-Length") is None583 ):584 # Set Content-Length to 0 for methods that can have a body585 # but don't provide one. (i.e. not GET or HEAD)586 self.headers["Content-Length"] = "0"587588 def prepare_auth(self, auth, url=""):589 """Prepares the given HTTP auth data."""590591 # If no Auth is explicitly provided, extract it from the URL first.592 if auth is None:593 url_auth = get_auth_from_url(self.url)594 auth = url_auth if any(url_auth) else None595596 if auth:597 if isinstance(auth, tuple) and len(auth) == 2:598 # special-case basic HTTP auth599 auth = HTTPBasicAuth(*auth)600601 # Allow auth to make its changes.602 r = auth(self)603604 # Update self to reflect the auth changes.605 self.__dict__.update(r.__dict__)606607 # Recompute Content-Length608 self.prepare_content_length(self.body)609610 def prepare_cookies(self, cookies):611 """Prepares the given HTTP cookie data.612613 This function eventually generates a ``Cookie`` header from the614 given cookies using cookielib. Due to cookielib's design, the header615 will not be regenerated if it already exists, meaning this function616 can only be called once for the life of the617 :class:`PreparedRequest <PreparedRequest>` object. Any subsequent calls618 to ``prepare_cookies`` will have no actual effect, unless the "Cookie"619 header is removed beforehand.620 """621 if isinstance(cookies, cookielib.CookieJar):622 self._cookies = cookies623 else:624 self._cookies = cookiejar_from_dict(cookies)625626 cookie_header = get_cookie_header(self._cookies, self)627 if cookie_header is not None:628 self.headers["Cookie"] = cookie_header629630 def prepare_hooks(self, hooks):631 """Prepares the given hooks."""632 # hooks can be passed as None to the prepare method and to this633 # method. To prevent iterating over None, simply use an empty list634 # if hooks is False-y635 hooks = hooks or []636 for event in hooks:637 self.register_hook(event, hooks[event])638639640class Response:641 """The :class:`Response <Response>` object, which contains a642 server's response to an HTTP request.643 """644645 __attrs__ = [646 "_content",647 "status_code",648 "headers",649 "url",650 "history",651 "encoding",652 "reason",653 "cookies",654 "elapsed",655 "request",656 ]657658 def __init__(self):659 self._content = False660 self._content_consumed = False661 self._next = None662663 #: Integer Code of responded HTTP Status, e.g. 404 or 200.664 self.status_code = None665666 #: Case-insensitive Dictionary of Response Headers.667 #: For example, ``headers['content-encoding']`` will return the668 #: value of a ``'Content-Encoding'`` response header.669 self.headers = CaseInsensitiveDict()670671 #: File-like object representation of response (for advanced usage).672 #: Use of ``raw`` requires that ``stream=True`` be set on the request.673 #: This requirement does not apply for use internally to Requests.674 self.raw = None675676 #: Final URL location of Response.677 self.url = None678679 #: Encoding to decode with when accessing r.text.680 self.encoding = None681682 #: A list of :class:`Response <Response>` objects from683 #: the history of the Request. Any redirect responses will end684 #: up here. The list is sorted from the oldest to the most recent request.685 self.history = []686687 #: Textual reason of responded HTTP Status, e.g. "Not Found" or "OK".688 self.reason = None689690 #: A CookieJar of Cookies the server sent back.691 self.cookies = cookiejar_from_dict({})692693 #: The amount of time elapsed between sending the request694 #: and the arrival of the response (as a timedelta).695 #: This property specifically measures the time taken between sending696 #: the first byte of the request and finishing parsing the headers. It697 #: is therefore unaffected by consuming the response content or the698 #: value of the ``stream`` keyword argument.699 self.elapsed = datetime.timedelta(0)700701 #: The :class:`PreparedRequest <PreparedRequest>` object to which this702 #: is a response.703 self.request = None704705 def __enter__(self):706 return self707708 def __exit__(self, *args):709 self.close()710711 def __getstate__(self):712 # Consume everything; accessing the content attribute makes713 # sure the content has been fully read.714 if not self._content_consumed:715 self.content716717 return {attr: getattr(self, attr, None) for attr in self.__attrs__}718719 def __setstate__(self, state):720 for name, value in state.items():721 setattr(self, name, value)722723 # pickled objects do not have .raw724 setattr(self, "_content_consumed", True)725 setattr(self, "raw", None)726727 def __repr__(self):728 return f"<Response [{self.status_code}]>"729730 def __bool__(self):731 """Returns True if :attr:`status_code` is less than 400.732733 This attribute checks if the status code of the response is between734 400 and 600 to see if there was a client error or a server error. If735 the status code, is between 200 and 400, this will return True. This736 is **not** a check to see if the response code is ``200 OK``.737 """738 return self.ok739740 def __nonzero__(self):741 """Returns True if :attr:`status_code` is less than 400.742743 This attribute checks if the status code of the response is between744 400 and 600 to see if there was a client error or a server error. If745 the status code, is between 200 and 400, this will return True. This746 is **not** a check to see if the response code is ``200 OK``.747 """748 return self.ok749750 def __iter__(self):751 """Allows you to use a response as an iterator."""752 return self.iter_content(128)753754 @property755 def ok(self):756 """Returns True if :attr:`status_code` is less than 400, False if not.757758 This attribute checks if the status code of the response is between759 400 and 600 to see if there was a client error or a server error. If760 the status code is between 200 and 400, this will return True. This761 is **not** a check to see if the response code is ``200 OK``.762 """763 try:764 self.raise_for_status()765 except HTTPError:766 return False767 return True768769 @property770 def is_redirect(self):771 """True if this Response is a well-formed HTTP redirect that could have772 been processed automatically (by :meth:`Session.resolve_redirects`).773 """774 return "location" in self.headers and self.status_code in REDIRECT_STATI775776 @property777 def is_permanent_redirect(self):778 """True if this Response one of the permanent versions of redirect."""779 return "location" in self.headers and self.status_code in (780 codes.moved_permanently,781 codes.permanent_redirect,782 )783784 @property785 def next(self):786 """Returns a PreparedRequest for the next request in a redirect chain, if there is one."""787 return self._next788789 @property790 def apparent_encoding(self):791 """The apparent encoding, provided by the charset_normalizer or chardet libraries."""792 return chardet.detect(self.content)["encoding"]793794 def iter_content(self, chunk_size=1, decode_unicode=False):795 """Iterates over the response data. When stream=True is set on the796 request, this avoids reading the content at once into memory for797 large responses. The chunk size is the number of bytes it should798 read into memory. This is not necessarily the length of each item799 returned as decoding can take place.800801 chunk_size must be of type int or None. A value of None will802 function differently depending on the value of `stream`.803 stream=True will read data as it arrives in whatever size the804 chunks are received. If stream=False, data is returned as805 a single chunk.806807 If decode_unicode is True, content will be decoded using the best808 available encoding based on the response.809 """810811 def generate():812 # Special case for urllib3.813 if hasattr(self.raw, "stream"):814 try:815 yield from self.raw.stream(chunk_size, decode_content=True)816 except ProtocolError as e:817 raise ChunkedEncodingError(e)818 except DecodeError as e:819 raise ContentDecodingError(e)820 except ReadTimeoutError as e:821 raise ConnectionError(e)822 except SSLError as e:823 raise RequestsSSLError(e)824 else:825 # Standard file-like object.826 while True:827 chunk = self.raw.read(chunk_size)828 if not chunk:829 break830 yield chunk831832 self._content_consumed = True833834 if self._content_consumed and isinstance(self._content, bool):835 raise StreamConsumedError()836 elif chunk_size is not None and not isinstance(chunk_size, int):837 raise TypeError(838 f"chunk_size must be an int, it is instead a {type(chunk_size)}."839 )840 # simulate reading small chunks of the content841 reused_chunks = iter_slices(self._content, chunk_size)842843 stream_chunks = generate()844845 chunks = reused_chunks if self._content_consumed else stream_chunks846847 if decode_unicode:848 chunks = stream_decode_response_unicode(chunks, self)849850 return chunks851852 def iter_lines(853 self, chunk_size=ITER_CHUNK_SIZE, decode_unicode=False, delimiter=None854 ):855 """Iterates over the response data, one line at a time. When856 stream=True is set on the request, this avoids reading the857 content at once into memory for large responses.858859 .. note:: This method is not reentrant safe.860 """861862 pending = None863864 for chunk in self.iter_content(865 chunk_size=chunk_size, decode_unicode=decode_unicode866 ):867 if pending is not None:868 chunk = pending + chunk869870 if delimiter:871 lines = chunk.split(delimiter)872 else:873 lines = chunk.splitlines()874875 if lines and lines[-1] and chunk and lines[-1][-1] == chunk[-1]:876 pending = lines.pop()877 else:878 pending = None879880 yield from lines881882 if pending is not None:883 yield pending884885 @property886 def content(self):887 """Content of the response, in bytes."""888889 if self._content is False:890 # Read the contents.891 if self._content_consumed:892 raise RuntimeError("The content for this response was already consumed")893894 if self.status_code == 0 or self.raw is None:895 self._content = None896 else:897 self._content = b"".join(self.iter_content(CONTENT_CHUNK_SIZE)) or b""898899 self._content_consumed = True900 # don't need to release the connection; that's been handled by urllib3901 # since we exhausted the data.902 return self._content903904 @property905 def text(self):906 """Content of the response, in unicode.907908 If Response.encoding is None, encoding will be guessed using909 ``charset_normalizer`` or ``chardet``.910911 The encoding of the response content is determined based solely on HTTP912 headers, following RFC 2616 to the letter. If you can take advantage of913 non-HTTP knowledge to make a better guess at the encoding, you should914 set ``r.encoding`` appropriately before accessing this property.915 """916917 # Try charset from content-type918 content = None919 encoding = self.encoding920921 if not self.content:922 return ""923924 # Fallback to auto-detected encoding.925 if self.encoding is None:926 encoding = self.apparent_encoding927928 # Decode unicode from given encoding.929 try:930 content = str(self.content, encoding, errors="replace")931 except (LookupError, TypeError):932 # A LookupError is raised if the encoding was not found which could933 # indicate a misspelling or similar mistake.934 #935 # A TypeError can be raised if encoding is None936 #937 # So we try blindly encoding.938 content = str(self.content, errors="replace")939940 return content941942 def json(self, **kwargs):943 r"""Returns the json-encoded content of a response, if any.944945 :param \*\*kwargs: Optional arguments that ``json.loads`` takes.946 :raises requests.exceptions.JSONDecodeError: If the response body does not947 contain valid json.948 """949950 if not self.encoding and self.content and len(self.content) > 3:951 # No encoding set. JSON RFC 4627 section 3 states we should expect952 # UTF-8, -16 or -32. Detect which one to use; If the detection or953 # decoding fails, fall back to `self.text` (using charset_normalizer to make954 # a best guess).955 encoding = guess_json_utf(self.content)956 if encoding is not None:957 try:958 return complexjson.loads(self.content.decode(encoding), **kwargs)959 except UnicodeDecodeError:960 # Wrong UTF codec detected; usually because it's not UTF-8961 # but some other 8-bit codec. This is an RFC violation,962 # and the server didn't bother to tell us what codec *was*963 # used.964 pass965 except JSONDecodeError as e:966 raise RequestsJSONDecodeError(e.msg, e.doc, e.pos)967968 try:969 return complexjson.loads(self.text, **kwargs)970 except JSONDecodeError as e:971 # Catch JSON-related errors and raise as requests.JSONDecodeError972 # This aliases json.JSONDecodeError and simplejson.JSONDecodeError973 raise RequestsJSONDecodeError(e.msg, e.doc, e.pos)974975 @property976 def links(self):977 """Returns the parsed header links of the response, if any."""978979 header = self.headers.get("link")980981 resolved_links = {}982983 if header:984 links = parse_header_links(header)985986 for link in links:987 key = link.get("rel") or link.get("url")988 resolved_links[key] = link989990 return resolved_links991992 def raise_for_status(self):993 """Raises :class:`HTTPError`, if one occurred."""994995 http_error_msg = ""996 if isinstance(self.reason, bytes):997 # We attempt to decode utf-8 first because some servers998 # choose to localize their reason strings. If the string999 # isn't utf-8, we fall back to iso-8859-1 for all other1000 # encodings. (See PR #3538)1001 try:1002 reason = self.reason.decode("utf-8")1003 except UnicodeDecodeError:1004 reason = self.reason.decode("iso-8859-1")1005 else:1006 reason = self.reason10071008 if 400 <= self.status_code < 500:1009 http_error_msg = (1010 f"{self.status_code} Client Error: {reason} for url: {self.url}"1011 )10121013 elif 500 <= self.status_code < 600:1014 http_error_msg = (1015 f"{self.status_code} Server Error: {reason} for url: {self.url}"1016 )10171018 if http_error_msg:1019 raise HTTPError(http_error_msg, response=self)10201021 def close(self):1022 """Releases the connection back to the pool. Once this method has been1023 called the underlying ``raw`` object must not be accessed again.10241025 *Note: Should not normally need to be called explicitly.*1026 """1027 if not self._content_consumed:1028 self.raw.close()10291030 release_conn = getattr(self.raw, "release_conn", None)1031 if release_conn is not None:1032 release_conn()
added:src/requests/packages.py+28 added
1import sys23try:4 import chardet5except ImportError:6 import warnings78 import charset_normalizer as chardet910 warnings.filterwarnings("ignore", "Trying to detect", module="charset_normalizer")1112# This code exists for backwards compatibility reasons.13# I don't like it either. Just look the other way. :)1415for package in ("urllib3", "idna"):16 locals()[package] = __import__(package)17 # This traversal is apparently necessary such that the identities are18 # preserved (requests.packages.urllib3.* is urllib3.*)19 for mod in list(sys.modules):20 if mod == package or mod.startswith(f"{package}."):21 sys.modules[f"requests.packages.{mod}"] = sys.modules[mod]2223target = chardet.__name__24for mod in list(sys.modules):25 if mod == target or mod.startswith(f"{target}."):26 target = target.replace(target, "chardet")27 sys.modules[f"requests.packages.{target}"] = sys.modules[mod]28# Kinda cool, though, right?
added:src/requests/sessions.py+831 added
1"""2requests.sessions3~~~~~~~~~~~~~~~~~45This module provides a Session object to manage and persist settings across6requests (cookies, auth, proxies).7"""8import os9import sys10import time11from collections import OrderedDict12from datetime import timedelta1314from ._internal_utils import to_native_string15from .adapters import HTTPAdapter16from .auth import _basic_auth_str17from .compat import Mapping, cookielib, urljoin, urlparse18from .cookies import (19 RequestsCookieJar,20 cookiejar_from_dict,21 extract_cookies_to_jar,22 merge_cookies,23)24from .exceptions import (25 ChunkedEncodingError,26 ContentDecodingError,27 InvalidSchema,28 TooManyRedirects,29)30from .hooks import default_hooks, dispatch_hook3132# formerly defined here, reexposed here for backward compatibility33from .models import ( # noqa: F40134 DEFAULT_REDIRECT_LIMIT,35 REDIRECT_STATI,36 PreparedRequest,37 Request,38)39from .status_codes import codes40from .structures import CaseInsensitiveDict41from .utils import ( # noqa: F40142 DEFAULT_PORTS,43 default_headers,44 get_auth_from_url,45 get_environ_proxies,46 get_netrc_auth,47 requote_uri,48 resolve_proxies,49 rewind_body,50 should_bypass_proxies,51 to_key_val_list,52)5354# Preferred clock, based on which one is more accurate on a given system.55if sys.platform == "win32":56 preferred_clock = time.perf_counter57else:58 preferred_clock = time.time596061def merge_setting(request_setting, session_setting, dict_class=OrderedDict):62 """Determines appropriate setting for a given request, taking into account63 the explicit setting on that request, and the setting in the session. If a64 setting is a dictionary, they will be merged together using `dict_class`65 """6667 if session_setting is None:68 return request_setting6970 if request_setting is None:71 return session_setting7273 # Bypass if not a dictionary (e.g. verify)74 if not (75 isinstance(session_setting, Mapping) and isinstance(request_setting, Mapping)76 ):77 return request_setting7879 merged_setting = dict_class(to_key_val_list(session_setting))80 merged_setting.update(to_key_val_list(request_setting))8182 # Remove keys that are set to None. Extract keys first to avoid altering83 # the dictionary during iteration.84 none_keys = [k for (k, v) in merged_setting.items() if v is None]85 for key in none_keys:86 del merged_setting[key]8788 return merged_setting899091def merge_hooks(request_hooks, session_hooks, dict_class=OrderedDict):92 """Properly merges both requests and session hooks.9394 This is necessary because when request_hooks == {'response': []}, the95 merge breaks Session hooks entirely.96 """97 if session_hooks is None or session_hooks.get("response") == []:98 return request_hooks99100 if request_hooks is None or request_hooks.get("response") == []:101 return session_hooks102103 return merge_setting(request_hooks, session_hooks, dict_class)104105106class SessionRedirectMixin:107 def get_redirect_target(self, resp):108 """Receives a Response. Returns a redirect URI or ``None``"""109 # Due to the nature of how requests processes redirects this method will110 # be called at least once upon the original response and at least twice111 # on each subsequent redirect response (if any).112 # If a custom mixin is used to handle this logic, it may be advantageous113 # to cache the redirect location onto the response object as a private114 # attribute.115 if resp.is_redirect:116 location = resp.headers["location"]117 # Currently the underlying http module on py3 decode headers118 # in latin1, but empirical evidence suggests that latin1 is very119 # rarely used with non-ASCII characters in HTTP headers.120 # It is more likely to get UTF8 header rather than latin1.121 # This causes incorrect handling of UTF8 encoded location headers.122 # To solve this, we re-encode the location in latin1.123 location = location.encode("latin1")124 return to_native_string(location, "utf8")125 return None126127 def should_strip_auth(self, old_url, new_url):128 """Decide whether Authorization header should be removed when redirecting"""129 old_parsed = urlparse(old_url)130 new_parsed = urlparse(new_url)131 if old_parsed.hostname != new_parsed.hostname:132 return True133 # Special case: allow http -> https redirect when using the standard134 # ports. This isn't specified by RFC 7235, but is kept to avoid135 # breaking backwards compatibility with older versions of requests136 # that allowed any redirects on the same host.137 if (138 old_parsed.scheme == "http"139 and old_parsed.port in (80, None)140 and new_parsed.scheme == "https"141 and new_parsed.port in (443, None)142 ):143 return False144145 # Handle default port usage corresponding to scheme.146 changed_port = old_parsed.port != new_parsed.port147 changed_scheme = old_parsed.scheme != new_parsed.scheme148 default_port = (DEFAULT_PORTS.get(old_parsed.scheme, None), None)149 if (150 not changed_scheme151 and old_parsed.port in default_port152 and new_parsed.port in default_port153 ):154 return False155156 # Standard case: root URI must match157 return changed_port or changed_scheme158159 def resolve_redirects(160 self,161 resp,162 req,163 stream=False,164 timeout=None,165 verify=True,166 cert=None,167 proxies=None,168 yield_requests=False,169 **adapter_kwargs,170 ):171 """Receives a Response. Returns a generator of Responses or Requests."""172173 hist = [] # keep track of history174175 url = self.get_redirect_target(resp)176 previous_fragment = urlparse(req.url).fragment177 while url:178 prepared_request = req.copy()179180 # Update history and keep track of redirects.181 # resp.history must ignore the original request in this loop182 hist.append(resp)183 resp.history = hist[1:]184185 try:186 resp.content # Consume socket so it can be released187 except (ChunkedEncodingError, ContentDecodingError, RuntimeError):188 resp.raw.read(decode_content=False)189190 if len(resp.history) >= self.max_redirects:191 raise TooManyRedirects(192 f"Exceeded {self.max_redirects} redirects.", response=resp193 )194195 # Release the connection back into the pool.196 resp.close()197198 # Handle redirection without scheme (see: RFC 1808 Section 4)199 if url.startswith("//"):200 parsed_rurl = urlparse(resp.url)201 url = ":".join([to_native_string(parsed_rurl.scheme), url])202203 # Normalize url case and attach previous fragment if needed (RFC 7231 7.1.2)204 parsed = urlparse(url)205 if parsed.fragment == "" and previous_fragment:206 parsed = parsed._replace(fragment=previous_fragment)207 elif parsed.fragment:208 previous_fragment = parsed.fragment209 url = parsed.geturl()210211 # Facilitate relative 'location' headers, as allowed by RFC 7231.212 # (e.g. '/path/to/resource' instead of 'http://domain.tld/path/to/resource')213 # Compliant with RFC3986, we percent encode the url.214 if not parsed.netloc:215 url = urljoin(resp.url, requote_uri(url))216 else:217 url = requote_uri(url)218219 prepared_request.url = to_native_string(url)220221 self.rebuild_method(prepared_request, resp)222223 # https://github.com/psf/requests/issues/1084224 if resp.status_code not in (225 codes.temporary_redirect,226 codes.permanent_redirect,227 ):228 # https://github.com/psf/requests/issues/3490229 purged_headers = ("Content-Length", "Content-Type", "Transfer-Encoding")230 for header in purged_headers:231 prepared_request.headers.pop(header, None)232 prepared_request.body = None233234 headers = prepared_request.headers235 headers.pop("Cookie", None)236237 # Extract any cookies sent on the response to the cookiejar238 # in the new request. Because we've mutated our copied prepared239 # request, use the old one that we haven't yet touched.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)243244 # Rebuild auth and proxy information.245 proxies = self.rebuild_proxies(prepared_request, proxies)246 self.rebuild_auth(prepared_request, resp)247248 # A failed tell() sets `_body_position` to `object()`. This non-None249 # value ensures `rewindable` will be True, allowing us to raise an250 # UnrewindableBodyError, instead of hanging the connection.251 rewindable = prepared_request._body_position is not None and (252 "Content-Length" in headers or "Transfer-Encoding" in headers253 )254255 # Attempt to rewind consumed file-like object.256 if rewindable:257 rewind_body(prepared_request)258259 # Override the original request.260 req = prepared_request261262 if yield_requests:263 yield req264 else:265 resp = self.send(266 req,267 stream=stream,268 timeout=timeout,269 verify=verify,270 cert=cert,271 proxies=proxies,272 allow_redirects=False,273 **adapter_kwargs,274 )275276 extract_cookies_to_jar(self.cookies, prepared_request, resp.raw)277278 # extract redirect url, if any, for the next loop279 url = self.get_redirect_target(resp)280 yield resp281282 def rebuild_auth(self, prepared_request, response):283 """When being redirected we may want to strip authentication from the284 request to avoid leaking credentials. This method intelligently removes285 and reapplies authentication where possible to avoid credential loss.286 """287 headers = prepared_request.headers288 url = prepared_request.url289290 if "Authorization" in headers and self.should_strip_auth(291 response.request.url, url292 ):293 # If we get redirected to a new host, we should strip out any294 # authentication headers.295 del headers["Authorization"]296297 # .netrc might have more auth for us on our new host.298 new_auth = get_netrc_auth(url) if self.trust_env else None299 if new_auth is not None:300 prepared_request.prepare_auth(new_auth)301302 def rebuild_proxies(self, prepared_request, proxies):303 """This method re-evaluates the proxy configuration by considering the304 environment variables. If we are redirected to a URL covered by305 NO_PROXY, we strip the proxy configuration. Otherwise, we set missing306 proxy keys for this URL (in case they were stripped by a previous307 redirect).308309 This method also replaces the Proxy-Authorization header where310 necessary.311312 :rtype: dict313 """314 headers = prepared_request.headers315 scheme = urlparse(prepared_request.url).scheme316 new_proxies = resolve_proxies(prepared_request, proxies, self.trust_env)317318 if "Proxy-Authorization" in headers:319 del headers["Proxy-Authorization"]320321 try:322 username, password = get_auth_from_url(new_proxies[scheme])323 except KeyError:324 username, password = None, None325326 # urllib3 handles proxy authorization for us in the standard adapter.327 # Avoid appending this to TLS tunneled requests where it may be leaked.328 if not scheme.startswith("https") and username and password:329 headers["Proxy-Authorization"] = _basic_auth_str(username, password)330331 return new_proxies332333 def rebuild_method(self, prepared_request, response):334 """When being redirected we may want to change the method of the request335 based on certain specs or browser behavior.336 """337 method = prepared_request.method338339 # https://tools.ietf.org/html/rfc7231#section-6.4.4340 if response.status_code == codes.see_other and method != "HEAD":341 method = "GET"342343 # Do what the browsers do, despite standards...344 # First, turn 302s into GETs.345 if response.status_code == codes.found and method != "HEAD":346 method = "GET"347348 # Second, if a POST is responded to with a 301, turn it into a GET.349 # This bizarre behaviour is explained in Issue 1704.350 if response.status_code == codes.moved and method == "POST":351 method = "GET"352353 prepared_request.method = method354355356class Session(SessionRedirectMixin):357 """A Requests session.358359 Provides cookie persistence, connection-pooling, and configuration.360361 Basic Usage::362363 >>> import requests364 >>> s = requests.Session()365 >>> s.get('https://httpbin.org/get')366 <Response [200]>367368 Or as a context manager::369370 >>> with requests.Session() as s:371 ... s.get('https://httpbin.org/get')372 <Response [200]>373 """374375 __attrs__ = [376 "headers",377 "cookies",378 "auth",379 "proxies",380 "hooks",381 "params",382 "verify",383 "cert",384 "adapters",385 "stream",386 "trust_env",387 "max_redirects",388 ]389390 def __init__(self):391 #: A case-insensitive dictionary of headers to be sent on each392 #: :class:`Request <Request>` sent from this393 #: :class:`Session <Session>`.394 self.headers = default_headers()395396 #: Default Authentication tuple or object to attach to397 #: :class:`Request <Request>`.398 self.auth = None399400 #: Dictionary mapping protocol or protocol and host to the URL of the proxy401 #: (e.g. {'http': 'foo.bar:3128', 'http://host.name': 'foo.bar:4012'}) to402 #: be used on each :class:`Request <Request>`.403 self.proxies = {}404405 #: Event-handling hooks.406 self.hooks = default_hooks()407408 #: Dictionary of querystring data to attach to each409 #: :class:`Request <Request>`. The dictionary values may be lists for410 #: representing multivalued query parameters.411 self.params = {}412413 #: Stream response content default.414 self.stream = False415416 #: SSL Verification default.417 #: Defaults to `True`, requiring requests to verify the TLS certificate at the418 #: remote end.419 #: If verify is set to `False`, requests will accept any TLS certificate420 #: presented by the server, and will ignore hostname mismatches and/or421 #: expired certificates, which will make your application vulnerable to422 #: man-in-the-middle (MitM) attacks.423 #: Only set this to `False` for testing.424 self.verify = True425426 #: SSL client certificate default, if String, path to ssl client427 #: cert file (.pem). If Tuple, ('cert', 'key') pair.428 self.cert = None429430 #: Maximum number of redirects allowed. If the request exceeds this431 #: limit, a :class:`TooManyRedirects` exception is raised.432 #: This defaults to requests.models.DEFAULT_REDIRECT_LIMIT, which is433 #: 30.434 self.max_redirects = DEFAULT_REDIRECT_LIMIT435436 #: Trust environment settings for proxy configuration, default437 #: authentication and similar.438 self.trust_env = True439440 #: A CookieJar containing all currently outstanding cookies set on this441 #: session. By default it is a442 #: :class:`RequestsCookieJar <requests.cookies.RequestsCookieJar>`, but443 #: may be any other ``cookielib.CookieJar`` compatible object.444 self.cookies = cookiejar_from_dict({})445446 # Default connection adapters.447 self.adapters = OrderedDict()448 self.mount("https://", HTTPAdapter())449 self.mount("http://", HTTPAdapter())450451 def __enter__(self):452 return self453454 def __exit__(self, *args):455 self.close()456457 def prepare_request(self, request):458 """Constructs a :class:`PreparedRequest <PreparedRequest>` for459 transmission and returns it. The :class:`PreparedRequest` has settings460 merged from the :class:`Request <Request>` instance and those of the461 :class:`Session`.462463 :param request: :class:`Request` instance to prepare with this464 session's settings.465 :rtype: requests.PreparedRequest466 """467 cookies = request.cookies or {}468469 # Bootstrap CookieJar.470 if not isinstance(cookies, cookielib.CookieJar):471 cookies = cookiejar_from_dict(cookies)472473 # Merge with session cookies474 merged_cookies = merge_cookies(475 merge_cookies(RequestsCookieJar(), self.cookies), cookies476 )477478 # Set environment's basic authentication if not explicitly set.479 auth = request.auth480 if self.trust_env and not auth and not self.auth:481 auth = get_netrc_auth(request.url)482483 p = PreparedRequest()484 p.prepare(485 method=request.method.upper(),486 url=request.url,487 files=request.files,488 data=request.data,489 json=request.json,490 headers=merge_setting(491 request.headers, self.headers, dict_class=CaseInsensitiveDict492 ),493 params=merge_setting(request.params, self.params),494 auth=merge_setting(auth, self.auth),495 cookies=merged_cookies,496 hooks=merge_hooks(request.hooks, self.hooks),497 )498 return p499500 def request(501 self,502 method,503 url,504 params=None,505 data=None,506 headers=None,507 cookies=None,508 files=None,509 auth=None,510 timeout=None,511 allow_redirects=True,512 proxies=None,513 hooks=None,514 stream=None,515 verify=None,516 cert=None,517 json=None,518 ):519 """Constructs a :class:`Request <Request>`, prepares it and sends it.520 Returns :class:`Response <Response>` object.521522 :param method: method for the new :class:`Request` object.523 :param url: URL for the new :class:`Request` object.524 :param params: (optional) Dictionary or bytes to be sent in the query525 string for the :class:`Request`.526 :param data: (optional) Dictionary, list of tuples, bytes, or file-like527 object to send in the body of the :class:`Request`.528 :param json: (optional) json to send in the body of the529 :class:`Request`.530 :param headers: (optional) Dictionary of HTTP Headers to send with the531 :class:`Request`.532 :param cookies: (optional) Dict or CookieJar object to send with the533 :class:`Request`.534 :param files: (optional) Dictionary of ``'filename': file-like-objects``535 for multipart encoding upload.536 :param auth: (optional) Auth tuple or callable to enable537 Basic/Digest/Custom HTTP Auth.538 :param timeout: (optional) How long to wait for the server to send539 data before giving up, as a float, or a :ref:`(connect timeout,540 read timeout) <timeouts>` tuple.541 :type timeout: float or tuple542 :param allow_redirects: (optional) Set to True by default.543 :type allow_redirects: bool544 :param proxies: (optional) Dictionary mapping protocol or protocol and545 hostname to the URL of the proxy.546 :param hooks: (optional) Dictionary mapping hook name to one event or547 list of events, event must be callable.548 :param stream: (optional) whether to immediately download the response549 content. Defaults to ``False``.550 :param verify: (optional) Either a boolean, in which case it controls whether we verify551 the server's TLS certificate, or a string, in which case it must be a path552 to a CA bundle to use. Defaults to ``True``. When set to553 ``False``, requests will accept any TLS certificate presented by554 the server, and will ignore hostname mismatches and/or expired555 certificates, which will make your application vulnerable to556 man-in-the-middle (MitM) attacks. Setting verify to ``False``557 may be useful during local development or testing.558 :param cert: (optional) if String, path to ssl client cert file (.pem).559 If Tuple, ('cert', 'key') pair.560 :rtype: requests.Response561 """562 # Create the Request.563 req = Request(564 method=method.upper(),565 url=url,566 headers=headers,567 files=files,568 data=data or {},569 json=json,570 params=params or {},571 auth=auth,572 cookies=cookies,573 hooks=hooks,574 )575 prep = self.prepare_request(req)576577 proxies = proxies or {}578579 settings = self.merge_environment_settings(580 prep.url, proxies, stream, verify, cert581 )582583 # Send the request.584 send_kwargs = {585 "timeout": timeout,586 "allow_redirects": allow_redirects,587 }588 send_kwargs.update(settings)589 resp = self.send(prep, **send_kwargs)590591 return resp592593 def get(self, url, **kwargs):594 r"""Sends a GET request. Returns :class:`Response` object.595596 :param url: URL for the new :class:`Request` object.597 :param \*\*kwargs: Optional arguments that ``request`` takes.598 :rtype: requests.Response599 """600601 kwargs.setdefault("allow_redirects", True)602 return self.request("GET", url, **kwargs)603604 def options(self, url, **kwargs):605 r"""Sends a OPTIONS request. Returns :class:`Response` object.606607 :param url: URL for the new :class:`Request` object.608 :param \*\*kwargs: Optional arguments that ``request`` takes.609 :rtype: requests.Response610 """611612 kwargs.setdefault("allow_redirects", True)613 return self.request("OPTIONS", url, **kwargs)614615 def head(self, url, **kwargs):616 r"""Sends a HEAD request. Returns :class:`Response` object.617618 :param url: URL for the new :class:`Request` object.619 :param \*\*kwargs: Optional arguments that ``request`` takes.620 :rtype: requests.Response621 """622623 kwargs.setdefault("allow_redirects", False)624 return self.request("HEAD", url, **kwargs)625626 def post(self, url, data=None, json=None, **kwargs):627 r"""Sends a POST request. Returns :class:`Response` object.628629 :param url: URL for the new :class:`Request` object.630 :param data: (optional) Dictionary, list of tuples, bytes, or file-like631 object to send in the body of the :class:`Request`.632 :param json: (optional) json to send in the body of the :class:`Request`.633 :param \*\*kwargs: Optional arguments that ``request`` takes.634 :rtype: requests.Response635 """636637 return self.request("POST", url, data=data, json=json, **kwargs)638639 def put(self, url, data=None, **kwargs):640 r"""Sends a PUT request. Returns :class:`Response` object.641642 :param url: URL for the new :class:`Request` object.643 :param data: (optional) Dictionary, list of tuples, bytes, or file-like644 object to send in the body of the :class:`Request`.645 :param \*\*kwargs: Optional arguments that ``request`` takes.646 :rtype: requests.Response647 """648649 return self.request("PUT", url, data=data, **kwargs)650651 def patch(self, url, data=None, **kwargs):652 r"""Sends a PATCH request. Returns :class:`Response` object.653654 :param url: URL for the new :class:`Request` object.655 :param data: (optional) Dictionary, list of tuples, bytes, or file-like656 object to send in the body of the :class:`Request`.657 :param \*\*kwargs: Optional arguments that ``request`` takes.658 :rtype: requests.Response659 """660661 return self.request("PATCH", url, data=data, **kwargs)662663 def delete(self, url, **kwargs):664 r"""Sends a DELETE request. Returns :class:`Response` object.665666 :param url: URL for the new :class:`Request` object.667 :param \*\*kwargs: Optional arguments that ``request`` takes.668 :rtype: requests.Response669 """670671 return self.request("DELETE", url, **kwargs)672673 def send(self, request, **kwargs):674 """Send a given PreparedRequest.675676 :rtype: requests.Response677 """678 # Set defaults that the hooks can utilize to ensure they always have679 # the correct parameters to reproduce the previous request.680 kwargs.setdefault("stream", self.stream)681 kwargs.setdefault("verify", self.verify)682 kwargs.setdefault("cert", self.cert)683 if "proxies" not in kwargs:684 kwargs["proxies"] = resolve_proxies(request, self.proxies, self.trust_env)685686 # It's possible that users might accidentally send a Request object.687 # Guard against that specific failure case.688 if isinstance(request, Request):689 raise ValueError("You can only send PreparedRequests.")690691 # Set up variables needed for resolve_redirects and dispatching of hooks692 allow_redirects = kwargs.pop("allow_redirects", True)693 stream = kwargs.get("stream")694 hooks = request.hooks695696 # Get the appropriate adapter to use697 adapter = self.get_adapter(url=request.url)698699 # Start time (approximately) of the request700 start = preferred_clock()701702 # Send the request703 r = adapter.send(request, **kwargs)704705 # Total elapsed time of the request (approximately)706 elapsed = preferred_clock() - start707 r.elapsed = timedelta(seconds=elapsed)708709 # Response manipulation hooks710 r = dispatch_hook("response", hooks, r, **kwargs)711712 # Persist cookies713 if r.history:714 # If the hooks create history then we want those cookies too715 for resp in r.history:716 extract_cookies_to_jar(self.cookies, resp.request, resp.raw)717718 extract_cookies_to_jar(self.cookies, request, r.raw)719720 # Resolve redirects if allowed.721 if allow_redirects:722 # Redirect resolving generator.723 gen = self.resolve_redirects(r, request, **kwargs)724 history = [resp for resp in gen]725 else:726 history = []727728 # Shuffle things around if there's history.729 if history:730 # Insert the first (original) request at the start731 history.insert(0, r)732 # Get the last request made733 r = history.pop()734 r.history = history735736 # If redirects aren't being followed, store the response on the Request for Response.next().737 if not allow_redirects:738 try:739 r._next = next(740 self.resolve_redirects(r, request, yield_requests=True, **kwargs)741 )742 except StopIteration:743 pass744745 if not stream:746 r.content747748 return r749750 def merge_environment_settings(self, url, proxies, stream, verify, cert):751 """752 Check the environment and merge it with some settings.753754 :rtype: dict755 """756 # Gather clues from the surrounding environment.757 if self.trust_env:758 # Set environment's proxies.759 no_proxy = proxies.get("no_proxy") if proxies is not None else None760 env_proxies = get_environ_proxies(url, no_proxy=no_proxy)761 for k, v in env_proxies.items():762 proxies.setdefault(k, v)763764 # Look for requests environment configuration765 # and be compatible with cURL.766 if verify is True or verify is None:767 verify = (768 os.environ.get("REQUESTS_CA_BUNDLE")769 or os.environ.get("CURL_CA_BUNDLE")770 or verify771 )772773 # Merge all the kwargs.774 proxies = merge_setting(proxies, self.proxies)775 stream = merge_setting(stream, self.stream)776 verify = merge_setting(verify, self.verify)777 cert = merge_setting(cert, self.cert)778779 return {"proxies": proxies, "stream": stream, "verify": verify, "cert": cert}780781 def get_adapter(self, url):782 """783 Returns the appropriate connection adapter for the given URL.784785 :rtype: requests.adapters.BaseAdapter786 """787 for prefix, adapter in self.adapters.items():788 if url.lower().startswith(prefix.lower()):789 return adapter790791 # Nothing matches :-/792 raise InvalidSchema(f"No connection adapters were found for {url!r}")793794 def close(self):795 """Closes all adapters and as such the session"""796 for v in self.adapters.values():797 v.close()798799 def mount(self, prefix, adapter):800 """Registers a connection adapter to a prefix.801802 Adapters are sorted in descending order by prefix length.803 """804 self.adapters[prefix] = adapter805 keys_to_move = [k for k in self.adapters if len(k) < len(prefix)]806807 for key in keys_to_move:808 self.adapters[key] = self.adapters.pop(key)809810 def __getstate__(self):811 state = {attr: getattr(self, attr, None) for attr in self.__attrs__}812 return state813814 def __setstate__(self, state):815 for attr, value in state.items():816 setattr(self, attr, value)817818819def session():820 """821 Returns a :class:`Session` for context-management.822823 .. deprecated:: 1.0.0824825 This method has been deprecated since version 1.0.0 and is only kept for826 backwards compatibility. New code should use :class:`~requests.sessions.Session`827 to create a session. This may be removed at a future date.828829 :rtype: Session830 """831 return Session()
added:src/requests/status_codes.py+128 added
1r"""2The ``codes`` object defines a mapping from common names for HTTP statuses3to their numerical codes, accessible either as attributes or as dictionary4items.56Example::78 >>> import requests9 >>> requests.codes['temporary_redirect']10 30711 >>> requests.codes.teapot12 41813 >>> requests.codes['\o/']14 2001516Some codes have multiple names, and both upper- and lower-case versions of17the names are allowed. For example, ``codes.ok``, ``codes.OK``, and18``codes.okay`` all correspond to the HTTP status code 200.19"""2021from .structures import LookupDict2223_codes = {24 # Informational.25 100: ("continue",),26 101: ("switching_protocols",),27 102: ("processing",),28 103: ("checkpoint",),29 122: ("uri_too_long", "request_uri_too_long"),30 200: ("ok", "okay", "all_ok", "all_okay", "all_good", "\\o/", "✓"),31 201: ("created",),32 202: ("accepted",),33 203: ("non_authoritative_info", "non_authoritative_information"),34 204: ("no_content",),35 205: ("reset_content", "reset"),36 206: ("partial_content", "partial"),37 207: ("multi_status", "multiple_status", "multi_stati", "multiple_stati"),38 208: ("already_reported",),39 226: ("im_used",),40 # Redirection.41 300: ("multiple_choices",),42 301: ("moved_permanently", "moved", "\\o-"),43 302: ("found",),44 303: ("see_other", "other"),45 304: ("not_modified",),46 305: ("use_proxy",),47 306: ("switch_proxy",),48 307: ("temporary_redirect", "temporary_moved", "temporary"),49 308: (50 "permanent_redirect",51 "resume_incomplete",52 "resume",53 ), # "resume" and "resume_incomplete" to be removed in 3.054 # Client Error.55 400: ("bad_request", "bad"),56 401: ("unauthorized",),57 402: ("payment_required", "payment"),58 403: ("forbidden",),59 404: ("not_found", "-o-"),60 405: ("method_not_allowed", "not_allowed"),61 406: ("not_acceptable",),62 407: ("proxy_authentication_required", "proxy_auth", "proxy_authentication"),63 408: ("request_timeout", "timeout"),64 409: ("conflict",),65 410: ("gone",),66 411: ("length_required",),67 412: ("precondition_failed", "precondition"),68 413: ("request_entity_too_large",),69 414: ("request_uri_too_large",),70 415: ("unsupported_media_type", "unsupported_media", "media_type"),71 416: (72 "requested_range_not_satisfiable",73 "requested_range",74 "range_not_satisfiable",75 ),76 417: ("expectation_failed",),77 418: ("im_a_teapot", "teapot", "i_am_a_teapot"),78 421: ("misdirected_request",),79 422: ("unprocessable_entity", "unprocessable"),80 423: ("locked",),81 424: ("failed_dependency", "dependency"),82 425: ("unordered_collection", "unordered"),83 426: ("upgrade_required", "upgrade"),84 428: ("precondition_required", "precondition"),85 429: ("too_many_requests", "too_many"),86 431: ("header_fields_too_large", "fields_too_large"),87 444: ("no_response", "none"),88 449: ("retry_with", "retry"),89 450: ("blocked_by_windows_parental_controls", "parental_controls"),90 451: ("unavailable_for_legal_reasons", "legal_reasons"),91 499: ("client_closed_request",),92 # Server Error.93 500: ("internal_server_error", "server_error", "/o\\", "✗"),94 501: ("not_implemented",),95 502: ("bad_gateway",),96 503: ("service_unavailable", "unavailable"),97 504: ("gateway_timeout",),98 505: ("http_version_not_supported", "http_version"),99 506: ("variant_also_negotiates",),100 507: ("insufficient_storage",),101 509: ("bandwidth_limit_exceeded", "bandwidth"),102 510: ("not_extended",),103 511: ("network_authentication_required", "network_auth", "network_authentication"),104}105106codes = LookupDict(name="status_codes")107108109def _init():110 for code, titles in _codes.items():111 for title in titles:112 setattr(codes, title, code)113 if not title.startswith(("\\", "/")):114 setattr(codes, title.upper(), code)115116 def doc(code):117 names = ", ".join(f"``{n}``" for n in _codes[code])118 return "* %d: %s" % (code, names)119120 global __doc__121 __doc__ = (122 __doc__ + "\n" + "\n".join(doc(code) for code in sorted(_codes))123 if __doc__ is not None124 else None125 )126127128_init()
added:src/requests/structures.py+99 added
1"""2requests.structures3~~~~~~~~~~~~~~~~~~~45Data structures that power Requests.6"""78from collections import OrderedDict910from .compat import Mapping, MutableMapping111213class CaseInsensitiveDict(MutableMapping):14 """A case-insensitive ``dict``-like object.1516 Implements all methods and operations of17 ``MutableMapping`` as well as dict's ``copy``. Also18 provides ``lower_items``.1920 All keys are expected to be strings. The structure remembers the21 case of the last key to be set, and ``iter(instance)``,22 ``keys()``, ``items()``, ``iterkeys()``, and ``iteritems()``23 will contain case-sensitive keys. However, querying and contains24 testing is case insensitive::2526 cid = CaseInsensitiveDict()27 cid['Accept'] = 'application/json'28 cid['aCCEPT'] == 'application/json' # True29 list(cid) == ['Accept'] # True3031 For example, ``headers['content-encoding']`` will return the32 value of a ``'Content-Encoding'`` response header, regardless33 of how the header name was originally stored.3435 If the constructor, ``.update``, or equality comparison36 operations are given keys that have equal ``.lower()``s, the37 behavior is undefined.38 """3940 def __init__(self, data=None, **kwargs):41 self._store = OrderedDict()42 if data is None:43 data = {}44 self.update(data, **kwargs)4546 def __setitem__(self, key, value):47 # Use the lowercased key for lookups, but store the actual48 # key alongside the value.49 self._store[key.lower()] = (key, value)5051 def __getitem__(self, key):52 return self._store[key.lower()][1]5354 def __delitem__(self, key):55 del self._store[key.lower()]5657 def __iter__(self):58 return (casedkey for casedkey, mappedvalue in self._store.values())5960 def __len__(self):61 return len(self._store)6263 def lower_items(self):64 """Like iteritems(), but with all lowercase keys."""65 return ((lowerkey, keyval[1]) for (lowerkey, keyval) in self._store.items())6667 def __eq__(self, other):68 if isinstance(other, Mapping):69 other = CaseInsensitiveDict(other)70 else:71 return NotImplemented72 # Compare insensitively73 return dict(self.lower_items()) == dict(other.lower_items())7475 # Copy is required76 def copy(self):77 return CaseInsensitiveDict(self._store.values())7879 def __repr__(self):80 return str(dict(self.items()))818283class LookupDict(dict):84 """Dictionary lookup object."""8586 def __init__(self, name=None):87 self.name = name88 super().__init__()8990 def __repr__(self):91 return f"<lookup '{self.name}'>"9293 def __getitem__(self, key):94 # We allow fall-through here, so values default to None9596 return self.__dict__.get(key, None)9798 def get(self, key, default=None):99 return self.__dict__.get(key, default)
added:src/requests/utils.py+1091 added
1"""2requests.utils3~~~~~~~~~~~~~~45This module provides utility functions that are used within Requests6that are also useful for external consumption.7"""89import codecs10import contextlib11import io12import os13import re14import socket15import struct16import sys17import tempfile18import warnings19import zipfile20from collections import OrderedDict2122from urllib3.util import make_headers, parse_url2324from . import certs25from .__version__ import __version__2627# to_native_string is unused here, but imported here for backwards compatibility28from ._internal_utils import ( # noqa: F40129 _HEADER_VALIDATORS_BYTE,30 _HEADER_VALIDATORS_STR,31 HEADER_VALIDATORS,32 to_native_string,33)34from .compat import (35 Mapping,36 basestring,37 bytes,38 getproxies,39 getproxies_environment,40 integer_types,41)42from .compat import parse_http_list as _parse_list_header43from .compat import (44 proxy_bypass,45 proxy_bypass_environment,46 quote,47 str,48 unquote,49 urlparse,50 urlunparse,51)52from .cookies import cookiejar_from_dict53from .exceptions import (54 FileModeWarning,55 InvalidHeader,56 InvalidURL,57 UnrewindableBodyError,58)59from .structures import CaseInsensitiveDict6061NETRC_FILES = (".netrc", "_netrc")6263DEFAULT_CA_BUNDLE_PATH = certs.where()6465DEFAULT_PORTS = {"http": 80, "https": 443}6667# Ensure that ', ' is used to preserve previous delimiter behavior.68DEFAULT_ACCEPT_ENCODING = ", ".join(69 re.split(r",\s*", make_headers(accept_encoding=True)["accept-encoding"])70)717273if sys.platform == "win32":74 # provide a proxy_bypass version on Windows without DNS lookups7576 def proxy_bypass_registry(host):77 try:78 import winreg79 except ImportError:80 return False8182 try:83 internetSettings = winreg.OpenKey(84 winreg.HKEY_CURRENT_USER,85 r"Software\Microsoft\Windows\CurrentVersion\Internet Settings",86 )87 # ProxyEnable could be REG_SZ or REG_DWORD, normalizing it88 proxyEnable = int(winreg.QueryValueEx(internetSettings, "ProxyEnable")[0])89 # ProxyOverride is almost always a string90 proxyOverride = winreg.QueryValueEx(internetSettings, "ProxyOverride")[0]91 except (OSError, ValueError):92 return False93 if not proxyEnable or not proxyOverride:94 return False9596 # make a check value list from the registry entry: replace the97 # '<local>' string by the localhost entry and the corresponding98 # canonical entry.99 proxyOverride = proxyOverride.split(";")100 # now check if we match one of the registry values.101 for test in proxyOverride:102 if test == "<local>":103 if "." not in host:104 return True105 test = test.replace(".", r"\.") # mask dots106 test = test.replace("*", r".*") # change glob sequence107 test = test.replace("?", r".") # change glob char108 if re.match(test, host, re.I):109 return True110 return False111112 def proxy_bypass(host): # noqa113 """Return True, if the host should be bypassed.114115 Checks proxy settings gathered from the environment, if specified,116 or the registry.117 """118 if getproxies_environment():119 return proxy_bypass_environment(host)120 else:121 return proxy_bypass_registry(host)122123124def dict_to_sequence(d):125 """Returns an internal sequence dictionary update."""126127 if hasattr(d, "items"):128 d = d.items()129130 return d131132133def super_len(o):134 total_length = None135 current_position = 0136137 if hasattr(o, "__len__"):138 total_length = len(o)139140 elif hasattr(o, "len"):141 total_length = o.len142143 elif hasattr(o, "fileno"):144 try:145 fileno = o.fileno()146 except (io.UnsupportedOperation, AttributeError):147 # AttributeError is a surprising exception, seeing as how we've just checked148 # that `hasattr(o, 'fileno')`. It happens for objects obtained via149 # `Tarfile.extractfile()`, per issue 5229.150 pass151 else:152 total_length = os.fstat(fileno).st_size153154 # Having used fstat to determine the file length, we need to155 # confirm that this file was opened up in binary mode.156 if "b" not in o.mode:157 warnings.warn(158 (159 "Requests has determined the content-length for this "160 "request using the binary size of the file: however, the "161 "file has been opened in text mode (i.e. without the 'b' "162 "flag in the mode). This may lead to an incorrect "163 "content-length. In Requests 3.0, support will be removed "164 "for files in text mode."165 ),166 FileModeWarning,167 )168169 if hasattr(o, "tell"):170 try:171 current_position = o.tell()172 except OSError:173 # This can happen in some weird situations, such as when the file174 # is actually a special file descriptor like stdin. In this175 # instance, we don't know what the length is, so set it to zero and176 # let requests chunk it instead.177 if total_length is not None:178 current_position = total_length179 else:180 if hasattr(o, "seek") and total_length is None:181 # StringIO and BytesIO have seek but no usable fileno182 try:183 # seek to end of file184 o.seek(0, 2)185 total_length = o.tell()186187 # seek back to current position to support188 # partially read file-like objects189 o.seek(current_position or 0)190 except OSError:191 total_length = 0192193 if total_length is None:194 total_length = 0195196 return max(0, total_length - current_position)197198199def get_netrc_auth(url, raise_errors=False):200 """Returns the Requests tuple auth for a given url from netrc."""201202 netrc_file = os.environ.get("NETRC")203 if netrc_file is not None:204 netrc_locations = (netrc_file,)205 else:206 netrc_locations = (f"~/{f}" for f in NETRC_FILES)207208 try:209 from netrc import NetrcParseError, netrc210211 netrc_path = None212213 for f in netrc_locations:214 try:215 loc = os.path.expanduser(f)216 except KeyError:217 # os.path.expanduser can fail when $HOME is undefined and218 # getpwuid fails. See https://bugs.python.org/issue20164 &219 # https://github.com/psf/requests/issues/1846220 return221222 if os.path.exists(loc):223 netrc_path = loc224 break225226 # Abort early if there isn't one.227 if netrc_path is None:228 return229230 ri = urlparse(url)231232 # Strip port numbers from netloc. This weird `if...encode`` dance is233 # used for Python 3.2, which doesn't support unicode literals.234 splitstr = b":"235 if isinstance(url, str):236 splitstr = splitstr.decode("ascii")237 host = ri.netloc.split(splitstr)[0]238239 try:240 _netrc = netrc(netrc_path).authenticators(host)241 if _netrc:242 # Return with login / password243 login_i = 0 if _netrc[0] else 1244 return (_netrc[login_i], _netrc[2])245 except (NetrcParseError, OSError):246 # If there was a parsing error or a permissions issue reading the file,247 # we'll just skip netrc auth unless explicitly asked to raise errors.248 if raise_errors:249 raise250251 # App Engine hackiness.252 except (ImportError, AttributeError):253 pass254255256def guess_filename(obj):257 """Tries to guess the filename of the given object."""258 name = getattr(obj, "name", None)259 if name and isinstance(name, basestring) and name[0] != "<" and name[-1] != ">":260 return os.path.basename(name)261262263def extract_zipped_paths(path):264 """Replace nonexistent paths that look like they refer to a member of a zip265 archive with the location of an extracted copy of the target, or else266 just return the provided path unchanged.267 """268 if os.path.exists(path):269 # this is already a valid path, no need to do anything further270 return path271272 # find the first valid part of the provided path and treat that as a zip archive273 # assume the rest of the path is the name of a member in the archive274 archive, member = os.path.split(path)275 while archive and not os.path.exists(archive):276 archive, prefix = os.path.split(archive)277 if not prefix:278 # If we don't check for an empty prefix after the split (in other words, archive remains unchanged after the split),279 # we _can_ end up in an infinite loop on a rare corner case affecting a small number of users280 break281 member = "/".join([prefix, member])282283 if not zipfile.is_zipfile(archive):284 return path285286 zip_file = zipfile.ZipFile(archive)287 if member not in zip_file.namelist():288 return path289290 # we have a valid zip archive and a valid member of that archive291 tmp = tempfile.gettempdir()292 extracted_path = os.path.join(tmp, member.split("/")[-1])293 if not os.path.exists(extracted_path):294 # use read + write to avoid the creating nested folders, we only want the file, avoids mkdir racing condition295 with atomic_open(extracted_path) as file_handler:296 file_handler.write(zip_file.read(member))297 return extracted_path298299300@contextlib.contextmanager301def atomic_open(filename):302 """Write a file to the disk in an atomic fashion"""303 tmp_descriptor, tmp_name = tempfile.mkstemp(dir=os.path.dirname(filename))304 try:305 with os.fdopen(tmp_descriptor, "wb") as tmp_handler:306 yield tmp_handler307 os.replace(tmp_name, filename)308 except BaseException:309 os.remove(tmp_name)310 raise311312313def from_key_val_list(value):314 """Take an object and test to see if it can be represented as a315 dictionary. Unless it can not be represented as such, return an316 OrderedDict, e.g.,317318 ::319320 >>> from_key_val_list([('key', 'val')])321 OrderedDict([('key', 'val')])322 >>> from_key_val_list('string')323 Traceback (most recent call last):324 ...325 ValueError: cannot encode objects that are not 2-tuples326 >>> from_key_val_list({'key': 'val'})327 OrderedDict([('key', 'val')])328329 :rtype: OrderedDict330 """331 if value is None:332 return None333334 if isinstance(value, (str, bytes, bool, int)):335 raise ValueError("cannot encode objects that are not 2-tuples")336337 return OrderedDict(value)338339340def to_key_val_list(value):341 """Take an object and test to see if it can be represented as a342 dictionary. If it can be, return a list of tuples, e.g.,343344 ::345346 >>> to_key_val_list([('key', 'val')])347 [('key', 'val')]348 >>> to_key_val_list({'key': 'val'})349 [('key', 'val')]350 >>> to_key_val_list('string')351 Traceback (most recent call last):352 ...353 ValueError: cannot encode objects that are not 2-tuples354355 :rtype: list356 """357 if value is None:358 return None359360 if isinstance(value, (str, bytes, bool, int)):361 raise ValueError("cannot encode objects that are not 2-tuples")362363 if isinstance(value, Mapping):364 value = value.items()365366 return list(value)367368369# From mitsuhiko/werkzeug (used with permission).370def parse_list_header(value):371 """Parse lists as described by RFC 2068 Section 2.372373 In particular, parse comma-separated lists where the elements of374 the list may include quoted-strings. A quoted-string could375 contain a comma. A non-quoted string could have quotes in the376 middle. Quotes are removed automatically after parsing.377378 It basically works like :func:`parse_set_header` just that items379 may appear multiple times and case sensitivity is preserved.380381 The return value is a standard :class:`list`:382383 >>> parse_list_header('token, "quoted value"')384 ['token', 'quoted value']385386 To create a header from the :class:`list` again, use the387 :func:`dump_header` function.388389 :param value: a string with a list header.390 :return: :class:`list`391 :rtype: list392 """393 result = []394 for item in _parse_list_header(value):395 if item[:1] == item[-1:] == '"':396 item = unquote_header_value(item[1:-1])397 result.append(item)398 return result399400401# From mitsuhiko/werkzeug (used with permission).402def parse_dict_header(value):403 """Parse lists of key, value pairs as described by RFC 2068 Section 2 and404 convert them into a python dict:405406 >>> d = parse_dict_header('foo="is a fish", bar="as well"')407 >>> type(d) is dict408 True409 >>> sorted(d.items())410 [('bar', 'as well'), ('foo', 'is a fish')]411412 If there is no value for a key it will be `None`:413414 >>> parse_dict_header('key_without_value')415 {'key_without_value': None}416417 To create a header from the :class:`dict` again, use the418 :func:`dump_header` function.419420 :param value: a string with a dict header.421 :return: :class:`dict`422 :rtype: dict423 """424 result = {}425 for item in _parse_list_header(value):426 if "=" not in item:427 result[item] = None428 continue429 name, value = item.split("=", 1)430 if value[:1] == value[-1:] == '"':431 value = unquote_header_value(value[1:-1])432 result[name] = value433 return result434435436# From mitsuhiko/werkzeug (used with permission).437def unquote_header_value(value, is_filename=False):438 r"""Unquotes a header value. (Reversal of :func:`quote_header_value`).439 This does not use the real unquoting but what browsers are actually440 using for quoting.441442 :param value: the header value to unquote.443 :rtype: str444 """445 if value and value[0] == value[-1] == '"':446 # this is not the real unquoting, but fixing this so that the447 # RFC is met will result in bugs with internet explorer and448 # probably some other browsers as well. IE for example is449 # uploading files with "C:\foo\bar.txt" as filename450 value = value[1:-1]451452 # if this is a filename and the starting characters look like453 # a UNC path, then just return the value without quotes. Using the454 # replace sequence below on a UNC path has the effect of turning455 # the leading double slash into a single slash and then456 # _fix_ie_filename() doesn't work correctly. See #458.457 if not is_filename or value[:2] != "\\\\":458 return value.replace("\\\\", "\\").replace('\\"', '"')459 return value460461462def dict_from_cookiejar(cj):463 """Returns a key/value dictionary from a CookieJar.464465 :param cj: CookieJar object to extract cookies from.466 :rtype: dict467 """468469 cookie_dict = {cookie.name: cookie.value for cookie in cj}470 return cookie_dict471472473def add_dict_to_cookiejar(cj, cookie_dict):474 """Returns a CookieJar from a key/value dictionary.475476 :param cj: CookieJar to insert cookies into.477 :param cookie_dict: Dict of key/values to insert into CookieJar.478 :rtype: CookieJar479 """480481 return cookiejar_from_dict(cookie_dict, cj)482483484def get_encodings_from_content(content):485 """Returns encodings from given content string.486487 :param content: bytestring to extract encodings from.488 """489 warnings.warn(490 (491 "In requests 3.0, get_encodings_from_content will be removed. For "492 "more information, please see the discussion on issue #2266. (This"493 " warning should only appear once.)"494 ),495 DeprecationWarning,496 )497498 charset_re = re.compile(r'<meta.*?charset=["\']*(.+?)["\'>]', flags=re.I)499 pragma_re = re.compile(r'<meta.*?content=["\']*;?charset=(.+?)["\'>]', flags=re.I)500 xml_re = re.compile(r'^<\?xml.*?encoding=["\']*(.+?)["\'>]')501502 return (503 charset_re.findall(content)504 + pragma_re.findall(content)505 + xml_re.findall(content)506 )507508509def _parse_content_type_header(header):510 """Returns content type and parameters from given header511512 :param header: string513 :return: tuple containing content type and dictionary of514 parameters515 """516517 tokens = header.split(";")518 content_type, params = tokens[0].strip(), tokens[1:]519 params_dict = {}520 items_to_strip = "\"' "521522 for param in params:523 param = param.strip()524 if param:525 key, value = param, True526 index_of_equals = param.find("=")527 if index_of_equals != -1:528 key = param[:index_of_equals].strip(items_to_strip)529 value = param[index_of_equals + 1 :].strip(items_to_strip)530 params_dict[key.lower()] = value531 return content_type, params_dict532533534def get_encoding_from_headers(headers):535 """Returns encodings from given HTTP Header Dict.536537 :param headers: dictionary to extract encoding from.538 :rtype: str539 """540541 content_type = headers.get("content-type")542543 if not content_type:544 return None545546 content_type, params = _parse_content_type_header(content_type)547548 if "charset" in params:549 return params["charset"].strip("'\"")550551 if "text" in content_type:552 return "ISO-8859-1"553554 if "application/json" in content_type:555 # Assume UTF-8 based on RFC 4627: https://www.ietf.org/rfc/rfc4627.txt since the charset was unset556 return "utf-8"557558559def stream_decode_response_unicode(iterator, r):560 """Stream decodes an iterator."""561562 if r.encoding is None:563 yield from iterator564 return565566 decoder = codecs.getincrementaldecoder(r.encoding)(errors="replace")567 for chunk in iterator:568 rv = decoder.decode(chunk)569 if rv:570 yield rv571 rv = decoder.decode(b"", final=True)572 if rv:573 yield rv574575576def iter_slices(string, slice_length):577 """Iterate over slices of a string."""578 pos = 0579 if slice_length is None or slice_length <= 0:580 slice_length = len(string)581 while pos < len(string):582 yield string[pos : pos + slice_length]583 pos += slice_length584585586def get_unicode_from_response(r):587 """Returns the requested content back in unicode.588589 :param r: Response object to get unicode content from.590591 Tried:592593 1. charset from content-type594 2. fall back and replace all unicode characters595596 :rtype: str597 """598 warnings.warn(599 (600 "In requests 3.0, get_unicode_from_response will be removed. For "601 "more information, please see the discussion on issue #2266. (This"602 " warning should only appear once.)"603 ),604 DeprecationWarning,605 )606607 tried_encodings = []608609 # Try charset from content-type610 encoding = get_encoding_from_headers(r.headers)611612 if encoding:613 try:614 return str(r.content, encoding)615 except UnicodeError:616 tried_encodings.append(encoding)617618 # Fall back:619 try:620 return str(r.content, encoding, errors="replace")621 except TypeError:622 return r.content623624625# The unreserved URI characters (RFC 3986)626UNRESERVED_SET = frozenset(627 "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz" + "0123456789-._~"628)629630631def unquote_unreserved(uri):632 """Un-escape any percent-escape sequences in a URI that are unreserved633 characters. This leaves all reserved, illegal and non-ASCII bytes encoded.634635 :rtype: str636 """637 parts = uri.split("%")638 for i in range(1, len(parts)):639 h = parts[i][0:2]640 if len(h) == 2 and h.isalnum():641 try:642 c = chr(int(h, 16))643 except ValueError:644 raise InvalidURL(f"Invalid percent-escape sequence: '{h}'")645646 if c in UNRESERVED_SET:647 parts[i] = c + parts[i][2:]648 else:649 parts[i] = f"%{parts[i]}"650 else:651 parts[i] = f"%{parts[i]}"652 return "".join(parts)653654655def requote_uri(uri):656 """Re-quote the given URI.657658 This function passes the given URI through an unquote/quote cycle to659 ensure that it is fully and consistently quoted.660661 :rtype: str662 """663 safe_with_percent = "!#$%&'()*+,/:;=?@[]~"664 safe_without_percent = "!#$&'()*+,/:;=?@[]~"665 try:666 # Unquote only the unreserved characters667 # Then quote only illegal characters (do not quote reserved,668 # unreserved, or '%')669 return quote(unquote_unreserved(uri), safe=safe_with_percent)670 except InvalidURL:671 # We couldn't unquote the given URI, so let's try quoting it, but672 # there may be unquoted '%'s in the URI. We need to make sure they're673 # properly quoted so they do not cause issues elsewhere.674 return quote(uri, safe=safe_without_percent)675676677def address_in_network(ip, net):678 """This function allows you to check if an IP belongs to a network subnet679680 Example: returns True if ip = 192.168.1.1 and net = 192.168.1.0/24681 returns False if ip = 192.168.1.1 and net = 192.168.100.0/24682683 :rtype: bool684 """685 ipaddr = struct.unpack("=L", socket.inet_aton(ip))[0]686 netaddr, bits = net.split("/")687 netmask = struct.unpack("=L", socket.inet_aton(dotted_netmask(int(bits))))[0]688 network = struct.unpack("=L", socket.inet_aton(netaddr))[0] & netmask689 return (ipaddr & netmask) == (network & netmask)690691692def dotted_netmask(mask):693 """Converts mask from /xx format to xxx.xxx.xxx.xxx694695 Example: if mask is 24 function returns 255.255.255.0696697 :rtype: str698 """699 bits = 0xFFFFFFFF ^ (1 << 32 - mask) - 1700 return socket.inet_ntoa(struct.pack(">I", bits))701702703def is_ipv4_address(string_ip):704 """705 :rtype: bool706 """707 try:708 socket.inet_aton(string_ip)709 except OSError:710 return False711 return True712713714def is_valid_cidr(string_network):715 """716 Very simple check of the cidr format in no_proxy variable.717718 :rtype: bool719 """720 if string_network.count("/") == 1:721 try:722 mask = int(string_network.split("/")[1])723 except ValueError:724 return False725726 if mask < 1 or mask > 32:727 return False728729 try:730 socket.inet_aton(string_network.split("/")[0])731 except OSError:732 return False733 else:734 return False735 return True736737738@contextlib.contextmanager739def set_environ(env_name, value):740 """Set the environment variable 'env_name' to 'value'741742 Save previous value, yield, and then restore the previous value stored in743 the environment variable 'env_name'.744745 If 'value' is None, do nothing"""746 value_changed = value is not None747 if value_changed:748 old_value = os.environ.get(env_name)749 os.environ[env_name] = value750 try:751 yield752 finally:753 if value_changed:754 if old_value is None:755 del os.environ[env_name]756 else:757 os.environ[env_name] = old_value758759760def should_bypass_proxies(url, no_proxy):761 """762 Returns whether we should bypass proxies or not.763764 :rtype: bool765 """766767 # Prioritize lowercase environment variables over uppercase768 # to keep a consistent behaviour with other http projects (curl, wget).769 def get_proxy(key):770 return os.environ.get(key) or os.environ.get(key.upper())771772 # First check whether no_proxy is defined. If it is, check that the URL773 # we're getting isn't in the no_proxy list.774 no_proxy_arg = no_proxy775 if no_proxy is None:776 no_proxy = get_proxy("no_proxy")777 parsed = urlparse(url)778779 if parsed.hostname is None:780 # URLs don't always have hostnames, e.g. file:/// urls.781 return True782783 if no_proxy:784 # We need to check whether we match here. We need to see if we match785 # the end of the hostname, both with and without the port.786 no_proxy = (host for host in no_proxy.replace(" ", "").split(",") if host)787788 if is_ipv4_address(parsed.hostname):789 for proxy_ip in no_proxy:790 if is_valid_cidr(proxy_ip):791 if address_in_network(parsed.hostname, proxy_ip):792 return True793 elif parsed.hostname == proxy_ip:794 # If no_proxy ip was defined in plain IP notation instead of cidr notation &795 # matches the IP of the index796 return True797 else:798 host_with_port = parsed.hostname799 if parsed.port:800 host_with_port += f":{parsed.port}"801802 for host in no_proxy:803 if parsed.hostname.endswith(host) or host_with_port.endswith(host):804 # The URL does match something in no_proxy, so we don't want805 # to apply the proxies on this URL.806 return True807808 with set_environ("no_proxy", no_proxy_arg):809 # parsed.hostname can be `None` in cases such as a file URI.810 try:811 bypass = proxy_bypass(parsed.hostname)812 except (TypeError, socket.gaierror):813 bypass = False814815 if bypass:816 return True817818 return False819820821def get_environ_proxies(url, no_proxy=None):822 """823 Return a dict of environment proxies.824825 :rtype: dict826 """827 if should_bypass_proxies(url, no_proxy=no_proxy):828 return {}829 else:830 return getproxies()831832833def select_proxy(url, proxies):834 """Select a proxy for the url, if applicable.835836 :param url: The url being for the request837 :param proxies: A dictionary of schemes or schemes and hosts to proxy URLs838 """839 proxies = proxies or {}840 urlparts = urlparse(url)841 if urlparts.hostname is None:842 return proxies.get(urlparts.scheme, proxies.get("all"))843844 proxy_keys = [845 urlparts.scheme + "://" + urlparts.hostname,846 urlparts.scheme,847 "all://" + urlparts.hostname,848 "all",849 ]850 proxy = None851 for proxy_key in proxy_keys:852 if proxy_key in proxies:853 proxy = proxies[proxy_key]854 break855856 return proxy857858859def resolve_proxies(request, proxies, trust_env=True):860 """This method takes proxy information from a request and configuration861 input to resolve a mapping of target proxies. This will consider settings862 such a NO_PROXY to strip proxy configurations.863864 :param request: Request or PreparedRequest865 :param proxies: A dictionary of schemes or schemes and hosts to proxy URLs866 :param trust_env: Boolean declaring whether to trust environment configs867868 :rtype: dict869 """870 proxies = proxies if proxies is not None else {}871 url = request.url872 scheme = urlparse(url).scheme873 no_proxy = proxies.get("no_proxy")874 new_proxies = proxies.copy()875876 if trust_env and not should_bypass_proxies(url, no_proxy=no_proxy):877 environ_proxies = get_environ_proxies(url, no_proxy=no_proxy)878879 proxy = environ_proxies.get(scheme, environ_proxies.get("all"))880881 if proxy:882 new_proxies.setdefault(scheme, proxy)883 return new_proxies884885886def default_user_agent(name="python-requests"):887 """888 Return a string representing the default user agent.889890 :rtype: str891 """892 return f"{name}/{__version__}"893894895def default_headers():896 """897 :rtype: requests.structures.CaseInsensitiveDict898 """899 return CaseInsensitiveDict(900 {901 "User-Agent": default_user_agent(),902 "Accept-Encoding": DEFAULT_ACCEPT_ENCODING,903 "Accept": "*/*",904 "Connection": "keep-alive",905 }906 )907908909def parse_header_links(value):910 """Return a list of parsed link headers proxies.911912 i.e. Link: <http:/.../front.jpeg>; rel=front; type="image/jpeg",<http://.../back.jpeg>; rel=back;type="image/jpeg"913914 :rtype: list915 """916917 links = []918919 replace_chars = " '\""920921 value = value.strip(replace_chars)922 if not value:923 return links924925 for val in re.split(", *<", value):926 try:927 url, params = val.split(";", 1)928 except ValueError:929 url, params = val, ""930931 link = {"url": url.strip("<> '\"")}932933 for param in params.split(";"):934 try:935 key, value = param.split("=")936 except ValueError:937 break938939 link[key.strip(replace_chars)] = value.strip(replace_chars)940941 links.append(link)942943 return links944945946# Null bytes; no need to recreate these on each call to guess_json_utf947_null = "\x00".encode("ascii") # encoding to ASCII for Python 3948_null2 = _null * 2949_null3 = _null * 3950951952def guess_json_utf(data):953 """954 :rtype: str955 """956 # JSON always starts with two ASCII characters, so detection is as957 # easy as counting the nulls and from their location and count958 # determine the encoding. Also detect a BOM, if present.959 sample = data[:4]960 if sample in (codecs.BOM_UTF32_LE, codecs.BOM_UTF32_BE):961 return "utf-32" # BOM included962 if sample[:3] == codecs.BOM_UTF8:963 return "utf-8-sig" # BOM included, MS style (discouraged)964 if sample[:2] in (codecs.BOM_UTF16_LE, codecs.BOM_UTF16_BE):965 return "utf-16" # BOM included966 nullcount = sample.count(_null)967 if nullcount == 0:968 return "utf-8"969 if nullcount == 2:970 if sample[::2] == _null2: # 1st and 3rd are null971 return "utf-16-be"972 if sample[1::2] == _null2: # 2nd and 4th are null973 return "utf-16-le"974 # Did not detect 2 valid UTF-16 ascii-range characters975 if nullcount == 3:976 if sample[:3] == _null3:977 return "utf-32-be"978 if sample[1:] == _null3:979 return "utf-32-le"980 # Did not detect a valid UTF-32 ascii-range character981 return None982983984def prepend_scheme_if_needed(url, new_scheme):985 """Given a URL that may or may not have a scheme, prepend the given scheme.986 Does not replace a present scheme with the one provided as an argument.987988 :rtype: str989 """990 parsed = parse_url(url)991 scheme, auth, host, port, path, query, fragment = parsed992993 # A defect in urlparse determines that there isn't a netloc present in some994 # urls. We previously assumed parsing was overly cautious, and swapped the995 # netloc and path. Due to a lack of tests on the original defect, this is996 # maintained with parse_url for backwards compatibility.997 netloc = parsed.netloc998 if not netloc:999 netloc, path = path, netloc10001001 if auth:1002 # parse_url doesn't provide the netloc with auth1003 # so we'll add it ourselves.1004 netloc = "@".join([auth, netloc])1005 if scheme is None:1006 scheme = new_scheme1007 if path is None:1008 path = ""10091010 return urlunparse((scheme, netloc, path, "", query, fragment))101110121013def get_auth_from_url(url):1014 """Given a url with authentication components, extract them into a tuple of1015 username,password.10161017 :rtype: (str,str)1018 """1019 parsed = urlparse(url)10201021 try:1022 auth = (unquote(parsed.username), unquote(parsed.password))1023 except (AttributeError, TypeError):1024 auth = ("", "")10251026 return auth102710281029def check_header_validity(header):1030 """Verifies that header parts don't contain leading whitespace1031 reserved characters, or return characters.10321033 :param header: tuple, in the format (name, value).1034 """1035 name, value = header1036 _validate_header_part(header, name, 0)1037 _validate_header_part(header, value, 1)103810391040def _validate_header_part(header, header_part, header_validator_index):1041 if isinstance(header_part, str):1042 validator = _HEADER_VALIDATORS_STR[header_validator_index]1043 elif isinstance(header_part, bytes):1044 validator = _HEADER_VALIDATORS_BYTE[header_validator_index]1045 else:1046 raise InvalidHeader(1047 f"Header part ({header_part!r}) from {header} "1048 f"must be of type str or bytes, not {type(header_part)}"1049 )10501051 if not validator.match(header_part):1052 header_kind = "name" if header_validator_index == 0 else "value"1053 raise InvalidHeader(1054 f"Invalid leading whitespace, reserved character(s), or return"1055 f"character(s) in header {header_kind}: {header_part!r}"1056 )105710581059def urldefragauth(url):1060 """1061 Given a url remove the fragment and the authentication part.10621063 :rtype: str1064 """1065 scheme, netloc, path, params, query, fragment = urlparse(url)10661067 # see func:`prepend_scheme_if_needed`1068 if not netloc:1069 netloc, path = path, netloc10701071 netloc = netloc.rsplit("@", 1)[-1]10721073 return urlunparse((scheme, netloc, path, params, query, ""))107410751076def rewind_body(prepared_request):1077 """Move file pointer back to its recorded starting position1078 so it can be read again on redirect.1079 """1080 body_seek = getattr(prepared_request.body, "seek", None)1081 if body_seek is not None and isinstance(1082 prepared_request._body_position, integer_types1083 ):1084 try:1085 body_seek(prepared_request._body_position)1086 except OSError:1087 raise UnrewindableBodyError(1088 "An error occurred when rewinding request body for redirect."1089 )1090 else:1091 raise UnrewindableBodyError("Unable to rewind request body for redirect.")
modified:Makefile+5 added-5 removed
1.PHONY: docs2init:3 pip install -r requirements-dev.txt3 python -m pip install -r requirements-dev.txt4test:5 # This runs all of the tests on all supported Python versions.6 tox -p7ci:8 pytest tests --junitxml=report.xml8 python -m pytest tests --junitxml=report.xml910test-readme:11 python setup.py check --restructuredtext --strict && ([ $$? -eq 0 ] && echo "README.rst and HISTORY.rst ok") || echo "Invalid markup in README.rst or HISTORY.rst!"1213flake8:14 flake8 --ignore=E501,F401,E128,E402,E731,F821 requests14 python -m flake8 src/requests1516coverage:17 pytest --cov-config .coveragerc --verbose --cov-report term --cov-report xml --cov=requests tests17 python -m pytest --cov-config .coveragerc --verbose --cov-report term --cov-report xml --cov=src/requests tests1819publish:20 pip install 'twine>=1.5.0'20 python -m pip install 'twine>=1.5.0'21 python setup.py sdist bdist_wheel22 twine upload dist/*23 rm -fr build dist .egg requests.egg-info24
3 unmodified lines
modified:pyproject.toml+2 added-5 removed
1[tool.isort]2profile = "black"3src_paths = ["requests", "test"]3src_paths = ["src/requests", "test"]4honor_noqa = true56[tool.pytest.ini_options]7addopts = "--doctest-modules"8doctest_optionflags = "NORMALIZE_WHITESPACE ELLIPSIS"9minversion = "6.2"10testpaths = [11 "requests",12 "tests",13]10testpaths = ["tests"]
modified:setup.cfg+2 added-2 removed
10 unmodified lines
1112[flake8]13ignore = E203, E501, W50314per-file-ignores =15 requests/__init__.py:E402, F40116 requests/compat.py:E402, F40115 src/requests/__init__.py:E402, F40116 src/requests/compat.py:E402, F40117 tests/compat.py:F401
modified:setup.py+2 added-2 removed
73 unmodified lines
74]7576about = {}77here = os.path.abspath(os.path.dirname(__file__))78with open(os.path.join(here, "requests", "__version__.py"), "r", "utf-8") as f:78with open(os.path.join(here, "src", "requests", "__version__.py"), "r", "utf-8") as f:79 exec(f.read(), about)8081with open("README.md", "r", "utf-8") as f:82 readme = f.read()
8 unmodified lines
91 author_email=about["__author_email__"],92 url=about["__url__"],93 packages=["requests"],94 package_data={"": ["LICENSE", "NOTICE"]},95 package_dir={"requests": "requests"},95 package_dir={"": "src"},96 include_package_data=True,97 python_requires=">=3.7",98 install_requires=requires,99 license=about["__license__"],
34 unmodified lines