m2m模型翻译
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

166 lines
5.2 KiB

6 months ago
  1. """
  2. Python HTTP library with thread-safe connection pooling, file post support, user friendly, and more
  3. """
  4. from __future__ import annotations
  5. # Set default logging handler to avoid "No handler found" warnings.
  6. import logging
  7. import typing
  8. import warnings
  9. from logging import NullHandler
  10. from . import exceptions
  11. from ._base_connection import _TYPE_BODY
  12. from ._collections import HTTPHeaderDict
  13. from ._version import __version__
  14. from .connectionpool import HTTPConnectionPool, HTTPSConnectionPool, connection_from_url
  15. from .filepost import _TYPE_FIELDS, encode_multipart_formdata
  16. from .poolmanager import PoolManager, ProxyManager, proxy_from_url
  17. from .response import BaseHTTPResponse, HTTPResponse
  18. from .util.request import make_headers
  19. from .util.retry import Retry
  20. from .util.timeout import Timeout
  21. # Ensure that Python is compiled with OpenSSL 1.1.1+
  22. # If the 'ssl' module isn't available at all that's
  23. # fine, we only care if the module is available.
  24. try:
  25. import ssl
  26. except ImportError:
  27. pass
  28. else:
  29. if not ssl.OPENSSL_VERSION.startswith("OpenSSL "): # Defensive:
  30. warnings.warn(
  31. "urllib3 v2.0 only supports OpenSSL 1.1.1+, currently "
  32. f"the 'ssl' module is compiled with {ssl.OPENSSL_VERSION!r}. "
  33. "See: https://github.com/urllib3/urllib3/issues/3020",
  34. exceptions.NotOpenSSLWarning,
  35. )
  36. elif ssl.OPENSSL_VERSION_INFO < (1, 1, 1): # Defensive:
  37. raise ImportError(
  38. "urllib3 v2.0 only supports OpenSSL 1.1.1+, currently "
  39. f"the 'ssl' module is compiled with {ssl.OPENSSL_VERSION!r}. "
  40. "See: https://github.com/urllib3/urllib3/issues/2168"
  41. )
  42. # === NOTE TO REPACKAGERS AND VENDORS ===
  43. # Please delete this block, this logic is only
  44. # for urllib3 being distributed via PyPI.
  45. # See: https://github.com/urllib3/urllib3/issues/2680
  46. try:
  47. import urllib3_secure_extra # type: ignore # noqa: F401
  48. except ModuleNotFoundError:
  49. pass
  50. else:
  51. warnings.warn(
  52. "'urllib3[secure]' extra is deprecated and will be removed "
  53. "in urllib3 v2.1.0. Read more in this issue: "
  54. "https://github.com/urllib3/urllib3/issues/2680",
  55. category=DeprecationWarning,
  56. stacklevel=2,
  57. )
  58. __author__ = "Andrey Petrov (andrey.petrov@shazow.net)"
  59. __license__ = "MIT"
  60. __version__ = __version__
  61. __all__ = (
  62. "HTTPConnectionPool",
  63. "HTTPHeaderDict",
  64. "HTTPSConnectionPool",
  65. "PoolManager",
  66. "ProxyManager",
  67. "HTTPResponse",
  68. "Retry",
  69. "Timeout",
  70. "add_stderr_logger",
  71. "connection_from_url",
  72. "disable_warnings",
  73. "encode_multipart_formdata",
  74. "make_headers",
  75. "proxy_from_url",
  76. "request",
  77. "BaseHTTPResponse",
  78. )
  79. logging.getLogger(__name__).addHandler(NullHandler())
  80. def add_stderr_logger(
  81. level: int = logging.DEBUG,
  82. ) -> logging.StreamHandler[typing.TextIO]:
  83. """
  84. Helper for quickly adding a StreamHandler to the logger. Useful for
  85. debugging.
  86. Returns the handler after adding it.
  87. """
  88. # This method needs to be in this __init__.py to get the __name__ correct
  89. # even if urllib3 is vendored within another package.
  90. logger = logging.getLogger(__name__)
  91. handler = logging.StreamHandler()
  92. handler.setFormatter(logging.Formatter("%(asctime)s %(levelname)s %(message)s"))
  93. logger.addHandler(handler)
  94. logger.setLevel(level)
  95. logger.debug("Added a stderr logging handler to logger: %s", __name__)
  96. return handler
  97. # ... Clean up.
  98. del NullHandler
  99. # All warning filters *must* be appended unless you're really certain that they
  100. # shouldn't be: otherwise, it's very hard for users to use most Python
  101. # mechanisms to silence them.
  102. # SecurityWarning's always go off by default.
  103. warnings.simplefilter("always", exceptions.SecurityWarning, append=True)
  104. # InsecurePlatformWarning's don't vary between requests, so we keep it default.
  105. warnings.simplefilter("default", exceptions.InsecurePlatformWarning, append=True)
  106. def disable_warnings(category: type[Warning] = exceptions.HTTPWarning) -> None:
  107. """
  108. Helper for quickly disabling all urllib3 warnings.
  109. """
  110. warnings.simplefilter("ignore", category)
  111. _DEFAULT_POOL = PoolManager()
  112. def request(
  113. method: str,
  114. url: str,
  115. *,
  116. body: _TYPE_BODY | None = None,
  117. fields: _TYPE_FIELDS | None = None,
  118. headers: typing.Mapping[str, str] | None = None,
  119. preload_content: bool | None = True,
  120. decode_content: bool | None = True,
  121. redirect: bool | None = True,
  122. retries: Retry | bool | int | None = None,
  123. timeout: Timeout | float | int | None = 3,
  124. json: typing.Any | None = None,
  125. ) -> BaseHTTPResponse:
  126. """
  127. A convenience, top-level request method. It uses a module-global ``PoolManager`` instance.
  128. Therefore, its side effects could be shared across dependencies relying on it.
  129. To avoid side effects create a new ``PoolManager`` instance and use it instead.
  130. The method does not accept low-level ``**urlopen_kw`` keyword arguments.
  131. """
  132. return _DEFAULT_POOL.request(
  133. method,
  134. url,
  135. body=body,
  136. fields=fields,
  137. headers=headers,
  138. preload_content=preload_content,
  139. decode_content=decode_content,
  140. redirect=redirect,
  141. retries=retries,
  142. timeout=timeout,
  143. json=json,
  144. )