Coverage for /pythoncovmergedfiles/medio/medio/usr/local/lib/python3.8/site-packages/urllib3/__init__.py: 72%

50 statements  

« prev     ^ index     » next       coverage.py v7.2.7, created at 2023-06-07 06:32 +0000

1""" 

2Python HTTP library with thread-safe connection pooling, file post support, user friendly, and more 

3""" 

4 

5from __future__ import annotations 

6 

7# Set default logging handler to avoid "No handler found" warnings. 

8import logging 

9import typing 

10import warnings 

11from logging import NullHandler 

12 

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 

24 

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 ) 

46 

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 ) 

63 

64__author__ = "Andrey Petrov (andrey.petrov@shazow.net)" 

65__license__ = "MIT" 

66__version__ = __version__ 

67 

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) 

85 

86logging.getLogger(__name__).addHandler(NullHandler()) 

87 

88 

89def add_stderr_logger( 

90 level: int = logging.DEBUG, 

91) -> logging.StreamHandler[typing.TextIO]: 

92 """ 

93 Helper for quickly adding a StreamHandler to the logger. Useful for 

94 debugging. 

95 

96 Returns the handler after adding it. 

97 """ 

98 # This method needs to be in this __init__.py to get the __name__ correct 

99 # even if urllib3 is vendored within another package. 

100 logger = logging.getLogger(__name__) 

101 handler = logging.StreamHandler() 

102 handler.setFormatter(logging.Formatter("%(asctime)s %(levelname)s %(message)s")) 

103 logger.addHandler(handler) 

104 logger.setLevel(level) 

105 logger.debug("Added a stderr logging handler to logger: %s", __name__) 

106 return handler 

107 

108 

109# ... Clean up. 

110del NullHandler 

111 

112 

113# All warning filters *must* be appended unless you're really certain that they 

114# shouldn't be: otherwise, it's very hard for users to use most Python 

115# mechanisms to silence them. 

116# SecurityWarning's always go off by default. 

117warnings.simplefilter("always", exceptions.SecurityWarning, append=True) 

118# InsecurePlatformWarning's don't vary between requests, so we keep it default. 

119warnings.simplefilter("default", exceptions.InsecurePlatformWarning, append=True) 

120 

121 

122def disable_warnings(category: type[Warning] = exceptions.HTTPWarning) -> None: 

123 """ 

124 Helper for quickly disabling all urllib3 warnings. 

125 """ 

126 warnings.simplefilter("ignore", category) 

127 

128 

129_DEFAULT_POOL = PoolManager() 

130 

131 

132def request( 

133 method: str, 

134 url: str, 

135 *, 

136 body: _TYPE_BODY | None = None, 

137 fields: _TYPE_FIELDS | None = None, 

138 headers: typing.Mapping[str, str] | None = None, 

139 preload_content: bool | None = True, 

140 decode_content: bool | None = True, 

141 redirect: bool | None = True, 

142 retries: Retry | bool | int | None = None, 

143 timeout: Timeout | float | int | None = 3, 

144 json: typing.Any | None = None, 

145) -> BaseHTTPResponse: 

146 """ 

147 A convenience, top-level request method. It uses a module-global ``PoolManager`` instance. 

148 Therefore, its side effects could be shared across dependencies relying on it. 

149 To avoid side effects create a new ``PoolManager`` instance and use it instead. 

150 The method does not accept low-level ``**urlopen_kw`` keyword arguments. 

151 """ 

152 

153 return _DEFAULT_POOL.request( 

154 method, 

155 url, 

156 body=body, 

157 fields=fields, 

158 headers=headers, 

159 preload_content=preload_content, 

160 decode_content=decode_content, 

161 redirect=redirect, 

162 retries=retries, 

163 timeout=timeout, 

164 json=json, 

165 )