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