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

48 statements  

« prev     ^ index     » next       coverage.py v7.2.7, created at 2023-06-07 06:35 +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 # fmt: off 

34 if ( 

35 not ssl.OPENSSL_VERSION.startswith("OpenSSL ") 

36 or ssl.OPENSSL_VERSION_INFO < (1, 1, 1) 

37 ): # Defensive: 

38 raise ImportError( 

39 "urllib3 v2.0 only supports OpenSSL 1.1.1+, currently " 

40 f"the 'ssl' module is compiled with {ssl.OPENSSL_VERSION}. " 

41 "See: https://github.com/urllib3/urllib3/issues/2168" 

42 ) 

43 # fmt: on 

44 

45# === NOTE TO REPACKAGERS AND VENDORS === 

46# Please delete this block, this logic is only 

47# for urllib3 being distributed via PyPI. 

48# See: https://github.com/urllib3/urllib3/issues/2680 

49try: 

50 import urllib3_secure_extra # type: ignore # noqa: F401 

51except ModuleNotFoundError: 

52 pass 

53else: 

54 warnings.warn( 

55 "'urllib3[secure]' extra is deprecated and will be removed " 

56 "in urllib3 v2.1.0. Read more in this issue: " 

57 "https://github.com/urllib3/urllib3/issues/2680", 

58 category=DeprecationWarning, 

59 stacklevel=2, 

60 ) 

61 

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

63__license__ = "MIT" 

64__version__ = __version__ 

65 

66__all__ = ( 

67 "HTTPConnectionPool", 

68 "HTTPHeaderDict", 

69 "HTTPSConnectionPool", 

70 "PoolManager", 

71 "ProxyManager", 

72 "HTTPResponse", 

73 "Retry", 

74 "Timeout", 

75 "add_stderr_logger", 

76 "connection_from_url", 

77 "disable_warnings", 

78 "encode_multipart_formdata", 

79 "make_headers", 

80 "proxy_from_url", 

81 "request", 

82) 

83 

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

85 

86 

87def add_stderr_logger( 

88 level: int = logging.DEBUG, 

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

90 """ 

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

92 debugging. 

93 

94 Returns the handler after adding it. 

95 """ 

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

97 # even if urllib3 is vendored within another package. 

98 logger = logging.getLogger(__name__) 

99 handler = logging.StreamHandler() 

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

101 logger.addHandler(handler) 

102 logger.setLevel(level) 

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

104 return handler 

105 

106 

107# ... Clean up. 

108del NullHandler 

109 

110 

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

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

113# mechanisms to silence them. 

114# SecurityWarning's always go off by default. 

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

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

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

118 

119 

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

121 """ 

122 Helper for quickly disabling all urllib3 warnings. 

123 """ 

124 warnings.simplefilter("ignore", category) 

125 

126 

127_DEFAULT_POOL = PoolManager() 

128 

129 

130def request( 

131 method: str, 

132 url: str, 

133 *, 

134 body: _TYPE_BODY | None = None, 

135 fields: _TYPE_FIELDS | None = None, 

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

137 preload_content: bool | None = True, 

138 decode_content: bool | None = True, 

139 redirect: bool | None = True, 

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

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

142 json: typing.Any | None = None, 

143) -> BaseHTTPResponse: 

144 """ 

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

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

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

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

149 """ 

150 

151 return _DEFAULT_POOL.request( 

152 method, 

153 url, 

154 body=body, 

155 fields=fields, 

156 headers=headers, 

157 preload_content=preload_content, 

158 decode_content=decode_content, 

159 redirect=redirect, 

160 retries=retries, 

161 timeout=timeout, 

162 json=json, 

163 )