__init__.py 5.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219
  1. # __
  2. # /__) _ _ _ _ _/ _
  3. # / ( (- (/ (/ (- _) / _)
  4. # /
  5. """
  6. Requests HTTP Library
  7. ~~~~~~~~~~~~~~~~~~~~~
  8. Requests is an HTTP library, written in Python, for human beings.
  9. Basic GET usage:
  10. >>> import requests
  11. >>> r = requests.get('https://www.python.org')
  12. >>> r.status_code
  13. 200
  14. >>> b'Python is a programming language' in r.content
  15. True
  16. ... or POST:
  17. >>> payload = dict(key1='value1', key2='value2')
  18. >>> r = requests.post('https://httpbin.org/post', data=payload)
  19. >>> print(r.text)
  20. {
  21. ...
  22. "form": {
  23. "key1": "value1",
  24. "key2": "value2"
  25. },
  26. ...
  27. }
  28. The other HTTP methods are supported - see `requests.api`. Full documentation
  29. is at <https://requests.readthedocs.io>.
  30. :copyright: (c) 2017 by Kenneth Reitz.
  31. :license: Apache 2.0, see LICENSE for more details.
  32. """
  33. from __future__ import annotations
  34. import warnings
  35. import urllib3
  36. from .exceptions import RequestsDependencyWarning
  37. try:
  38. from charset_normalizer import __version__ as charset_normalizer_version
  39. except ImportError:
  40. charset_normalizer_version = None
  41. try:
  42. from chardet import __version__ as chardet_version # type: ignore[import-not-found]
  43. except ImportError:
  44. chardet_version = None
  45. def check_compatibility(
  46. urllib3_version: str,
  47. chardet_version: str | None,
  48. charset_normalizer_version: str | None,
  49. ) -> None:
  50. urllib3_version_list = urllib3_version.split(".")[:3]
  51. assert urllib3_version_list != ["dev"] # Verify urllib3 isn't installed from git.
  52. # Sometimes, urllib3 only reports its version as 16.1.
  53. if len(urllib3_version_list) == 2:
  54. urllib3_version_list.append("0")
  55. # Check urllib3 for compatibility.
  56. major, minor, patch = urllib3_version_list # noqa: F811
  57. major, minor, patch = int(major), int(minor), int(patch)
  58. # urllib3 >= 1.21.1
  59. assert major >= 1
  60. if major == 1:
  61. assert minor >= 21
  62. # Check charset_normalizer for compatibility.
  63. if chardet_version:
  64. major, minor, patch = chardet_version.split(".")[:3]
  65. major, minor, patch = int(major), int(minor), int(patch)
  66. # chardet_version >= 3.0.2, < 8.0.0
  67. assert (3, 0, 2) <= (major, minor, patch) < (8, 0, 0)
  68. elif charset_normalizer_version:
  69. major, minor, patch = charset_normalizer_version.split(".")[:3]
  70. major, minor, patch = int(major), int(minor), int(patch)
  71. # charset_normalizer >= 2.0.0 < 4.0.0
  72. assert (2, 0, 0) <= (major, minor, patch) < (4, 0, 0)
  73. else:
  74. warnings.warn(
  75. "Unable to find acceptable character detection dependency "
  76. "(chardet or charset_normalizer).",
  77. RequestsDependencyWarning,
  78. )
  79. def _check_cryptography(cryptography_version: str) -> None:
  80. # cryptography < 1.3.4
  81. try:
  82. cryptography_version_list = list(map(int, cryptography_version.split(".")))
  83. except ValueError:
  84. return
  85. if cryptography_version_list < [1, 3, 4]:
  86. warning = f"Old version of cryptography ({cryptography_version_list}) may cause slowdown."
  87. warnings.warn(warning, RequestsDependencyWarning)
  88. # Check imported dependencies for compatibility.
  89. try:
  90. check_compatibility(
  91. urllib3.__version__, # type: ignore[reportPrivateImportUsage]
  92. chardet_version, # type: ignore[reportUnknownArgumentType]
  93. charset_normalizer_version,
  94. )
  95. except (AssertionError, ValueError):
  96. warnings.warn(
  97. f"urllib3 ({urllib3.__version__}) or chardet " # type: ignore[reportPrivateImportUsage]
  98. f"({chardet_version})/charset_normalizer ({charset_normalizer_version}) "
  99. "doesn't match a supported version!",
  100. RequestsDependencyWarning,
  101. )
  102. # Attempt to enable urllib3's fallback for SNI support
  103. # if the standard library doesn't support SNI or the
  104. # 'ssl' library isn't available.
  105. try:
  106. try:
  107. import ssl
  108. except ImportError:
  109. ssl = None
  110. if not getattr(ssl, "HAS_SNI", False):
  111. from urllib3.contrib import pyopenssl
  112. pyopenssl.inject_into_urllib3()
  113. # Check cryptography version
  114. from cryptography import ( # type: ignore[reportMissingImports]
  115. __version__ as cryptography_version, # type: ignore[reportUnknownVariableType]
  116. )
  117. _check_cryptography(cryptography_version) # type: ignore[reportUnknownArgumentType]
  118. except ImportError:
  119. pass
  120. # urllib3's DependencyWarnings should be silenced.
  121. from urllib3.exceptions import DependencyWarning
  122. warnings.simplefilter("ignore", DependencyWarning)
  123. # Set default logging handler to avoid "No handler found" warnings.
  124. import logging
  125. from logging import NullHandler
  126. from . import packages, utils
  127. from .__version__ import (
  128. __author__,
  129. __author_email__,
  130. __build__,
  131. __cake__,
  132. __copyright__,
  133. __description__,
  134. __license__,
  135. __title__,
  136. __url__,
  137. __version__,
  138. )
  139. from .api import delete, get, head, options, patch, post, put, request
  140. from .exceptions import (
  141. ConnectionError,
  142. ConnectTimeout,
  143. FileModeWarning,
  144. HTTPError,
  145. JSONDecodeError,
  146. ReadTimeout,
  147. RequestException,
  148. Timeout,
  149. TooManyRedirects,
  150. URLRequired,
  151. )
  152. from .models import PreparedRequest, Request, Response
  153. from .sessions import Session, session
  154. from .status_codes import codes
  155. __all__ = (
  156. "ConnectionError",
  157. "ConnectTimeout",
  158. "HTTPError",
  159. "JSONDecodeError",
  160. "PreparedRequest",
  161. "ReadTimeout",
  162. "Request",
  163. "RequestException",
  164. "Response",
  165. "Session",
  166. "Timeout",
  167. "TooManyRedirects",
  168. "URLRequired",
  169. "codes",
  170. "delete",
  171. "get",
  172. "head",
  173. "options",
  174. "packages",
  175. "patch",
  176. "post",
  177. "put",
  178. "request",
  179. "session",
  180. "utils",
  181. )
  182. logging.getLogger(__name__).addHandler(NullHandler())
  183. # FileModeWarnings go off per the default.
  184. warnings.simplefilter("default", FileModeWarning, append=True)