Funktionierender Prototyp des Serious Games zur Vermittlung von Wissen zu Software-Engineering-Arbeitsmodellen.
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.

__init__.py 5.2KB

1 year ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165
  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. )
  78. logging.getLogger(__name__).addHandler(NullHandler())
  79. def add_stderr_logger(
  80. level: int = logging.DEBUG,
  81. ) -> logging.StreamHandler[typing.TextIO]:
  82. """
  83. Helper for quickly adding a StreamHandler to the logger. Useful for
  84. debugging.
  85. Returns the handler after adding it.
  86. """
  87. # This method needs to be in this __init__.py to get the __name__ correct
  88. # even if urllib3 is vendored within another package.
  89. logger = logging.getLogger(__name__)
  90. handler = logging.StreamHandler()
  91. handler.setFormatter(logging.Formatter("%(asctime)s %(levelname)s %(message)s"))
  92. logger.addHandler(handler)
  93. logger.setLevel(level)
  94. logger.debug("Added a stderr logging handler to logger: %s", __name__)
  95. return handler
  96. # ... Clean up.
  97. del NullHandler
  98. # All warning filters *must* be appended unless you're really certain that they
  99. # shouldn't be: otherwise, it's very hard for users to use most Python
  100. # mechanisms to silence them.
  101. # SecurityWarning's always go off by default.
  102. warnings.simplefilter("always", exceptions.SecurityWarning, append=True)
  103. # InsecurePlatformWarning's don't vary between requests, so we keep it default.
  104. warnings.simplefilter("default", exceptions.InsecurePlatformWarning, append=True)
  105. def disable_warnings(category: type[Warning] = exceptions.HTTPWarning) -> None:
  106. """
  107. Helper for quickly disabling all urllib3 warnings.
  108. """
  109. warnings.simplefilter("ignore", category)
  110. _DEFAULT_POOL = PoolManager()
  111. def request(
  112. method: str,
  113. url: str,
  114. *,
  115. body: _TYPE_BODY | None = None,
  116. fields: _TYPE_FIELDS | None = None,
  117. headers: typing.Mapping[str, str] | None = None,
  118. preload_content: bool | None = True,
  119. decode_content: bool | None = True,
  120. redirect: bool | None = True,
  121. retries: Retry | bool | int | None = None,
  122. timeout: Timeout | float | int | None = 3,
  123. json: typing.Any | None = None,
  124. ) -> BaseHTTPResponse:
  125. """
  126. A convenience, top-level request method. It uses a module-global ``PoolManager`` instance.
  127. Therefore, its side effects could be shared across dependencies relying on it.
  128. To avoid side effects create a new ``PoolManager`` instance and use it instead.
  129. The method does not accept low-level ``**urlopen_kw`` keyword arguments.
  130. """
  131. return _DEFAULT_POOL.request(
  132. method,
  133. url,
  134. body=body,
  135. fields=fields,
  136. headers=headers,
  137. preload_content=preload_content,
  138. decode_content=decode_content,
  139. redirect=redirect,
  140. retries=retries,
  141. timeout=timeout,
  142. json=json,
  143. )