snowflake-connector-python 3.16.0__cp313-cp313-win_amd64.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (246) hide show
  1. snowflake/connector/__init__.py +96 -0
  2. snowflake/connector/_query_context_cache.py +276 -0
  3. snowflake/connector/_sql_util.py +48 -0
  4. snowflake/connector/_utils.py +70 -0
  5. snowflake/connector/arrow_context.py +203 -0
  6. snowflake/connector/auth/__init__.py +53 -0
  7. snowflake/connector/auth/_auth.py +586 -0
  8. snowflake/connector/auth/_http_server.py +220 -0
  9. snowflake/connector/auth/_oauth_base.py +400 -0
  10. snowflake/connector/auth/by_plugin.py +219 -0
  11. snowflake/connector/auth/default.py +36 -0
  12. snowflake/connector/auth/idtoken.py +72 -0
  13. snowflake/connector/auth/keypair.py +222 -0
  14. snowflake/connector/auth/no_auth.py +39 -0
  15. snowflake/connector/auth/oauth.py +49 -0
  16. snowflake/connector/auth/oauth_code.py +479 -0
  17. snowflake/connector/auth/oauth_credentials.py +66 -0
  18. snowflake/connector/auth/okta.py +335 -0
  19. snowflake/connector/auth/pat.py +39 -0
  20. snowflake/connector/auth/usrpwdmfa.py +69 -0
  21. snowflake/connector/auth/webbrowser.py +502 -0
  22. snowflake/connector/auth/workload_identity.py +94 -0
  23. snowflake/connector/azure_storage_client.py +276 -0
  24. snowflake/connector/backoff_policies.py +141 -0
  25. snowflake/connector/bind_upload_agent.py +89 -0
  26. snowflake/connector/cache.py +696 -0
  27. snowflake/connector/compat.py +127 -0
  28. snowflake/connector/config_manager.py +496 -0
  29. snowflake/connector/connection.py +2273 -0
  30. snowflake/connector/connection_diagnostic.py +776 -0
  31. snowflake/connector/constants.py +442 -0
  32. snowflake/connector/converter.py +785 -0
  33. snowflake/connector/converter_issue23517.py +87 -0
  34. snowflake/connector/converter_null.py +14 -0
  35. snowflake/connector/converter_snowsql.py +205 -0
  36. snowflake/connector/cursor.py +1951 -0
  37. snowflake/connector/dbapi.py +53 -0
  38. snowflake/connector/description.py +19 -0
  39. snowflake/connector/direct_file_operation_utils.py +88 -0
  40. snowflake/connector/encryption_util.py +220 -0
  41. snowflake/connector/errorcode.py +91 -0
  42. snowflake/connector/errors.py +615 -0
  43. snowflake/connector/externals_utils/__init__.py +0 -0
  44. snowflake/connector/externals_utils/externals_setup.py +27 -0
  45. snowflake/connector/feature.py +4 -0
  46. snowflake/connector/file_compression_type.py +118 -0
  47. snowflake/connector/file_lock.py +72 -0
  48. snowflake/connector/file_transfer_agent.py +1215 -0
  49. snowflake/connector/file_util.py +153 -0
  50. snowflake/connector/gcs_storage_client.py +474 -0
  51. snowflake/connector/gzip_decoder.py +85 -0
  52. snowflake/connector/local_storage_client.py +90 -0
  53. snowflake/connector/log_configuration.py +60 -0
  54. snowflake/connector/logging_utils/__init__.py +0 -0
  55. snowflake/connector/logging_utils/filters.py +72 -0
  56. snowflake/connector/nanoarrow_arrow_iterator.cp313-win_amd64.pyd +0 -0
  57. snowflake/connector/nanoarrow_cpp/ArrowIterator/ArrayConverter.cpp +60 -0
  58. snowflake/connector/nanoarrow_cpp/ArrowIterator/ArrayConverter.hpp +29 -0
  59. snowflake/connector/nanoarrow_cpp/ArrowIterator/BinaryConverter.cpp +19 -0
  60. snowflake/connector/nanoarrow_cpp/ArrowIterator/BinaryConverter.hpp +26 -0
  61. snowflake/connector/nanoarrow_cpp/ArrowIterator/BooleanConverter.cpp +21 -0
  62. snowflake/connector/nanoarrow_cpp/ArrowIterator/BooleanConverter.hpp +23 -0
  63. snowflake/connector/nanoarrow_cpp/ArrowIterator/CArrowChunkIterator.cpp +557 -0
  64. snowflake/connector/nanoarrow_cpp/ArrowIterator/CArrowChunkIterator.hpp +98 -0
  65. snowflake/connector/nanoarrow_cpp/ArrowIterator/CArrowIterator.cpp +125 -0
  66. snowflake/connector/nanoarrow_cpp/ArrowIterator/CArrowIterator.hpp +115 -0
  67. snowflake/connector/nanoarrow_cpp/ArrowIterator/CArrowTableIterator.cpp +1005 -0
  68. snowflake/connector/nanoarrow_cpp/ArrowIterator/CArrowTableIterator.hpp +127 -0
  69. snowflake/connector/nanoarrow_cpp/ArrowIterator/DateConverter.cpp +47 -0
  70. snowflake/connector/nanoarrow_cpp/ArrowIterator/DateConverter.hpp +46 -0
  71. snowflake/connector/nanoarrow_cpp/ArrowIterator/DecFloatConverter.cpp +83 -0
  72. snowflake/connector/nanoarrow_cpp/ArrowIterator/DecFloatConverter.hpp +35 -0
  73. snowflake/connector/nanoarrow_cpp/ArrowIterator/DecimalConverter.cpp +97 -0
  74. snowflake/connector/nanoarrow_cpp/ArrowIterator/DecimalConverter.hpp +72 -0
  75. snowflake/connector/nanoarrow_cpp/ArrowIterator/FixedSizeListConverter.cpp +73 -0
  76. snowflake/connector/nanoarrow_cpp/ArrowIterator/FixedSizeListConverter.hpp +28 -0
  77. snowflake/connector/nanoarrow_cpp/ArrowIterator/FloatConverter.cpp +30 -0
  78. snowflake/connector/nanoarrow_cpp/ArrowIterator/FloatConverter.hpp +35 -0
  79. snowflake/connector/nanoarrow_cpp/ArrowIterator/IColumnConverter.hpp +17 -0
  80. snowflake/connector/nanoarrow_cpp/ArrowIterator/IntConverter.cpp +23 -0
  81. snowflake/connector/nanoarrow_cpp/ArrowIterator/IntConverter.hpp +45 -0
  82. snowflake/connector/nanoarrow_cpp/ArrowIterator/IntervalConverter.cpp +71 -0
  83. snowflake/connector/nanoarrow_cpp/ArrowIterator/IntervalConverter.hpp +56 -0
  84. snowflake/connector/nanoarrow_cpp/ArrowIterator/LICENSE.txt +209 -0
  85. snowflake/connector/nanoarrow_cpp/ArrowIterator/MapConverter.cpp +75 -0
  86. snowflake/connector/nanoarrow_cpp/ArrowIterator/MapConverter.hpp +30 -0
  87. snowflake/connector/nanoarrow_cpp/ArrowIterator/ObjectConverter.cpp +46 -0
  88. snowflake/connector/nanoarrow_cpp/ArrowIterator/ObjectConverter.hpp +29 -0
  89. snowflake/connector/nanoarrow_cpp/ArrowIterator/Python/Common.cpp +8 -0
  90. snowflake/connector/nanoarrow_cpp/ArrowIterator/Python/Common.hpp +95 -0
  91. snowflake/connector/nanoarrow_cpp/ArrowIterator/Python/Helpers.cpp +57 -0
  92. snowflake/connector/nanoarrow_cpp/ArrowIterator/Python/Helpers.hpp +36 -0
  93. snowflake/connector/nanoarrow_cpp/ArrowIterator/SnowflakeType.cpp +34 -0
  94. snowflake/connector/nanoarrow_cpp/ArrowIterator/SnowflakeType.hpp +48 -0
  95. snowflake/connector/nanoarrow_cpp/ArrowIterator/StringConverter.cpp +19 -0
  96. snowflake/connector/nanoarrow_cpp/ArrowIterator/StringConverter.hpp +26 -0
  97. snowflake/connector/nanoarrow_cpp/ArrowIterator/TimeConverter.cpp +36 -0
  98. snowflake/connector/nanoarrow_cpp/ArrowIterator/TimeConverter.hpp +31 -0
  99. snowflake/connector/nanoarrow_cpp/ArrowIterator/TimeStampConverter.cpp +346 -0
  100. snowflake/connector/nanoarrow_cpp/ArrowIterator/TimeStampConverter.hpp +145 -0
  101. snowflake/connector/nanoarrow_cpp/ArrowIterator/Util/macros.hpp +14 -0
  102. snowflake/connector/nanoarrow_cpp/ArrowIterator/Util/time.cpp +65 -0
  103. snowflake/connector/nanoarrow_cpp/ArrowIterator/Util/time.hpp +68 -0
  104. snowflake/connector/nanoarrow_cpp/ArrowIterator/flatcc/flatcc_accessors.h +101 -0
  105. snowflake/connector/nanoarrow_cpp/ArrowIterator/flatcc/flatcc_alloc.h +127 -0
  106. snowflake/connector/nanoarrow_cpp/ArrowIterator/flatcc/flatcc_assert.h +45 -0
  107. snowflake/connector/nanoarrow_cpp/ArrowIterator/flatcc/flatcc_builder.h +1908 -0
  108. snowflake/connector/nanoarrow_cpp/ArrowIterator/flatcc/flatcc_emitter.h +215 -0
  109. snowflake/connector/nanoarrow_cpp/ArrowIterator/flatcc/flatcc_endian.h +125 -0
  110. snowflake/connector/nanoarrow_cpp/ArrowIterator/flatcc/flatcc_epilogue.h +7 -0
  111. snowflake/connector/nanoarrow_cpp/ArrowIterator/flatcc/flatcc_flatbuffers.h +55 -0
  112. snowflake/connector/nanoarrow_cpp/ArrowIterator/flatcc/flatcc_identifier.h +148 -0
  113. snowflake/connector/nanoarrow_cpp/ArrowIterator/flatcc/flatcc_iov.h +31 -0
  114. snowflake/connector/nanoarrow_cpp/ArrowIterator/flatcc/flatcc_prologue.h +8 -0
  115. snowflake/connector/nanoarrow_cpp/ArrowIterator/flatcc/flatcc_refmap.h +144 -0
  116. snowflake/connector/nanoarrow_cpp/ArrowIterator/flatcc/flatcc_rtconfig.h +162 -0
  117. snowflake/connector/nanoarrow_cpp/ArrowIterator/flatcc/flatcc_types.h +97 -0
  118. snowflake/connector/nanoarrow_cpp/ArrowIterator/flatcc/flatcc_verifier.h +239 -0
  119. snowflake/connector/nanoarrow_cpp/ArrowIterator/flatcc/portable/flatcc_portable.h +14 -0
  120. snowflake/connector/nanoarrow_cpp/ArrowIterator/flatcc/portable/paligned_alloc.h +210 -0
  121. snowflake/connector/nanoarrow_cpp/ArrowIterator/flatcc/portable/pattributes.h +84 -0
  122. snowflake/connector/nanoarrow_cpp/ArrowIterator/flatcc/portable/pdiagnostic.h +84 -0
  123. snowflake/connector/nanoarrow_cpp/ArrowIterator/flatcc/portable/pdiagnostic_pop.h +20 -0
  124. snowflake/connector/nanoarrow_cpp/ArrowIterator/flatcc/portable/pdiagnostic_push.h +51 -0
  125. snowflake/connector/nanoarrow_cpp/ArrowIterator/flatcc/portable/pendian.h +206 -0
  126. snowflake/connector/nanoarrow_cpp/ArrowIterator/flatcc/portable/pendian_detect.h +118 -0
  127. snowflake/connector/nanoarrow_cpp/ArrowIterator/flatcc/portable/pinline.h +19 -0
  128. snowflake/connector/nanoarrow_cpp/ArrowIterator/flatcc/portable/pinttypes.h +52 -0
  129. snowflake/connector/nanoarrow_cpp/ArrowIterator/flatcc/portable/portable.h +2 -0
  130. snowflake/connector/nanoarrow_cpp/ArrowIterator/flatcc/portable/portable_basic.h +25 -0
  131. snowflake/connector/nanoarrow_cpp/ArrowIterator/flatcc/portable/pstatic_assert.h +67 -0
  132. snowflake/connector/nanoarrow_cpp/ArrowIterator/flatcc/portable/pstdalign.h +162 -0
  133. snowflake/connector/nanoarrow_cpp/ArrowIterator/flatcc/portable/pstdint.h +898 -0
  134. snowflake/connector/nanoarrow_cpp/ArrowIterator/flatcc/portable/punaligned.h +190 -0
  135. snowflake/connector/nanoarrow_cpp/ArrowIterator/flatcc/portable/pversion.h +6 -0
  136. snowflake/connector/nanoarrow_cpp/ArrowIterator/flatcc/portable/pwarnings.h +52 -0
  137. snowflake/connector/nanoarrow_cpp/ArrowIterator/flatcc.c +3204 -0
  138. snowflake/connector/nanoarrow_cpp/ArrowIterator/nanoarrow.c +3217 -0
  139. snowflake/connector/nanoarrow_cpp/ArrowIterator/nanoarrow.h +3618 -0
  140. snowflake/connector/nanoarrow_cpp/ArrowIterator/nanoarrow.hpp +379 -0
  141. snowflake/connector/nanoarrow_cpp/ArrowIterator/nanoarrow_arrow_iterator.pyx +256 -0
  142. snowflake/connector/nanoarrow_cpp/ArrowIterator/nanoarrow_device.c +512 -0
  143. snowflake/connector/nanoarrow_cpp/ArrowIterator/nanoarrow_device.h +350 -0
  144. snowflake/connector/nanoarrow_cpp/ArrowIterator/nanoarrow_ipc.c +33273 -0
  145. snowflake/connector/nanoarrow_cpp/ArrowIterator/nanoarrow_ipc.h +397 -0
  146. snowflake/connector/nanoarrow_cpp/Logging/logging.cpp +100 -0
  147. snowflake/connector/nanoarrow_cpp/Logging/logging.hpp +49 -0
  148. snowflake/connector/network.py +1297 -0
  149. snowflake/connector/ocsp_asn1crypto.py +447 -0
  150. snowflake/connector/ocsp_snowflake.py +1883 -0
  151. snowflake/connector/options.py +131 -0
  152. snowflake/connector/pandas_tools.py +732 -0
  153. snowflake/connector/proxy.py +43 -0
  154. snowflake/connector/py.typed +0 -0
  155. snowflake/connector/result_batch.py +786 -0
  156. snowflake/connector/result_set.py +319 -0
  157. snowflake/connector/s3_storage_client.py +605 -0
  158. snowflake/connector/secret_detector.py +181 -0
  159. snowflake/connector/sf_dirs.py +64 -0
  160. snowflake/connector/sfbinaryformat.py +35 -0
  161. snowflake/connector/sfdatetime.py +345 -0
  162. snowflake/connector/snow_logging.py +144 -0
  163. snowflake/connector/sqlstate.py +9 -0
  164. snowflake/connector/ssd_internal_keys.py +30 -0
  165. snowflake/connector/ssl_wrap_socket.py +134 -0
  166. snowflake/connector/storage_client.py +478 -0
  167. snowflake/connector/telemetry.py +249 -0
  168. snowflake/connector/telemetry_oob.py +543 -0
  169. snowflake/connector/test_util.py +30 -0
  170. snowflake/connector/time_util.py +159 -0
  171. snowflake/connector/token_cache.py +402 -0
  172. snowflake/connector/tool/__init__.py +0 -0
  173. snowflake/connector/tool/dump_certs.py +57 -0
  174. snowflake/connector/tool/dump_ocsp_response.py +139 -0
  175. snowflake/connector/tool/dump_ocsp_response_cache.py +194 -0
  176. snowflake/connector/tool/probe_connection.py +69 -0
  177. snowflake/connector/url_util.py +49 -0
  178. snowflake/connector/util_text.py +301 -0
  179. snowflake/connector/vendored/__init__.py +3 -0
  180. snowflake/connector/vendored/requests/LICENSE +175 -0
  181. snowflake/connector/vendored/requests/__init__.py +169 -0
  182. snowflake/connector/vendored/requests/__version__.py +14 -0
  183. snowflake/connector/vendored/requests/_internal_utils.py +50 -0
  184. snowflake/connector/vendored/requests/adapters.py +537 -0
  185. snowflake/connector/vendored/requests/api.py +157 -0
  186. snowflake/connector/vendored/requests/auth.py +315 -0
  187. snowflake/connector/vendored/requests/certs.py +17 -0
  188. snowflake/connector/vendored/requests/compat.py +79 -0
  189. snowflake/connector/vendored/requests/cookies.py +561 -0
  190. snowflake/connector/vendored/requests/exceptions.py +140 -0
  191. snowflake/connector/vendored/requests/help.py +134 -0
  192. snowflake/connector/vendored/requests/hooks.py +33 -0
  193. snowflake/connector/vendored/requests/models.py +1033 -0
  194. snowflake/connector/vendored/requests/sessions.py +833 -0
  195. snowflake/connector/vendored/requests/status_codes.py +128 -0
  196. snowflake/connector/vendored/requests/structures.py +99 -0
  197. snowflake/connector/vendored/requests/utils.py +1093 -0
  198. snowflake/connector/vendored/urllib3/LICENSE.txt +21 -0
  199. snowflake/connector/vendored/urllib3/__init__.py +85 -0
  200. snowflake/connector/vendored/urllib3/_collections.py +355 -0
  201. snowflake/connector/vendored/urllib3/_version.py +2 -0
  202. snowflake/connector/vendored/urllib3/connection.py +572 -0
  203. snowflake/connector/vendored/urllib3/connectionpool.py +1137 -0
  204. snowflake/connector/vendored/urllib3/contrib/__init__.py +0 -0
  205. snowflake/connector/vendored/urllib3/contrib/_appengine_environ.py +36 -0
  206. snowflake/connector/vendored/urllib3/contrib/_securetransport/__init__.py +0 -0
  207. snowflake/connector/vendored/urllib3/contrib/_securetransport/bindings.py +519 -0
  208. snowflake/connector/vendored/urllib3/contrib/_securetransport/low_level.py +397 -0
  209. snowflake/connector/vendored/urllib3/contrib/appengine.py +314 -0
  210. snowflake/connector/vendored/urllib3/contrib/ntlmpool.py +130 -0
  211. snowflake/connector/vendored/urllib3/contrib/pyopenssl.py +509 -0
  212. snowflake/connector/vendored/urllib3/contrib/securetransport.py +920 -0
  213. snowflake/connector/vendored/urllib3/contrib/socks.py +216 -0
  214. snowflake/connector/vendored/urllib3/exceptions.py +323 -0
  215. snowflake/connector/vendored/urllib3/fields.py +274 -0
  216. snowflake/connector/vendored/urllib3/filepost.py +98 -0
  217. snowflake/connector/vendored/urllib3/packages/__init__.py +0 -0
  218. snowflake/connector/vendored/urllib3/packages/backports/__init__.py +0 -0
  219. snowflake/connector/vendored/urllib3/packages/backports/makefile.py +51 -0
  220. snowflake/connector/vendored/urllib3/packages/backports/weakref_finalize.py +155 -0
  221. snowflake/connector/vendored/urllib3/packages/six.py +1076 -0
  222. snowflake/connector/vendored/urllib3/poolmanager.py +540 -0
  223. snowflake/connector/vendored/urllib3/request.py +191 -0
  224. snowflake/connector/vendored/urllib3/response.py +885 -0
  225. snowflake/connector/vendored/urllib3/util/__init__.py +49 -0
  226. snowflake/connector/vendored/urllib3/util/connection.py +156 -0
  227. snowflake/connector/vendored/urllib3/util/proxy.py +57 -0
  228. snowflake/connector/vendored/urllib3/util/queue.py +22 -0
  229. snowflake/connector/vendored/urllib3/util/request.py +146 -0
  230. snowflake/connector/vendored/urllib3/util/response.py +107 -0
  231. snowflake/connector/vendored/urllib3/util/retry.py +620 -0
  232. snowflake/connector/vendored/urllib3/util/ssl_.py +495 -0
  233. snowflake/connector/vendored/urllib3/util/ssl_match_hostname.py +159 -0
  234. snowflake/connector/vendored/urllib3/util/ssltransport.py +221 -0
  235. snowflake/connector/vendored/urllib3/util/timeout.py +271 -0
  236. snowflake/connector/vendored/urllib3/util/url.py +435 -0
  237. snowflake/connector/vendored/urllib3/util/wait.py +152 -0
  238. snowflake/connector/version.py +3 -0
  239. snowflake/connector/wif_util.py +407 -0
  240. snowflake_connector_python-3.16.0.dist-info/METADATA +1475 -0
  241. snowflake_connector_python-3.16.0.dist-info/RECORD +246 -0
  242. snowflake_connector_python-3.16.0.dist-info/WHEEL +5 -0
  243. snowflake_connector_python-3.16.0.dist-info/entry_points.txt +4 -0
  244. snowflake_connector_python-3.16.0.dist-info/licenses/LICENSE.txt +202 -0
  245. snowflake_connector_python-3.16.0.dist-info/licenses/NOTICE +8 -0
  246. snowflake_connector_python-3.16.0.dist-info/top_level.txt +1 -0
@@ -0,0 +1,1093 @@
1
+ """
2
+ requests.utils
3
+ ~~~~~~~~~~~~~~
4
+
5
+ This module provides utility functions that are used within Requests
6
+ that are also useful for external consumption.
7
+ """
8
+
9
+ import codecs
10
+ import contextlib
11
+ import io
12
+ import os
13
+ import re
14
+ import socket
15
+ import struct
16
+ import sys
17
+ import tempfile
18
+ import warnings
19
+ import zipfile
20
+ from collections import OrderedDict
21
+
22
+ from ..urllib3.util import make_headers, parse_url
23
+ from . import certs
24
+ from .__version__ import __version__
25
+
26
+ # to_native_string is unused here, but imported here for backwards compatibility
27
+ from ._internal_utils import ( # noqa: F401
28
+ _HEADER_VALIDATORS_BYTE,
29
+ _HEADER_VALIDATORS_STR,
30
+ HEADER_VALIDATORS,
31
+ to_native_string,
32
+ )
33
+ from .compat import (
34
+ Mapping,
35
+ basestring,
36
+ bytes,
37
+ getproxies,
38
+ getproxies_environment,
39
+ integer_types,
40
+ )
41
+ from .compat import parse_http_list as _parse_list_header
42
+ from .compat import (
43
+ proxy_bypass,
44
+ proxy_bypass_environment,
45
+ quote,
46
+ str,
47
+ unquote,
48
+ urlparse,
49
+ urlunparse,
50
+ )
51
+ from .cookies import cookiejar_from_dict
52
+ from .exceptions import (
53
+ FileModeWarning,
54
+ InvalidHeader,
55
+ InvalidURL,
56
+ UnrewindableBodyError,
57
+ )
58
+ from .structures import CaseInsensitiveDict
59
+
60
+ NETRC_FILES = (".netrc", "_netrc")
61
+
62
+ DEFAULT_CA_BUNDLE_PATH = certs.where()
63
+
64
+ DEFAULT_PORTS = {"http": 80, "https": 443}
65
+
66
+ # Ensure that ', ' is used to preserve previous delimiter behavior.
67
+ DEFAULT_ACCEPT_ENCODING = ", ".join(
68
+ re.split(r",\s*", make_headers(accept_encoding=True)["accept-encoding"])
69
+ )
70
+
71
+
72
+ if sys.platform == "win32":
73
+ # provide a proxy_bypass version on Windows without DNS lookups
74
+
75
+ def proxy_bypass_registry(host):
76
+ try:
77
+ import winreg
78
+ except ImportError:
79
+ return False
80
+
81
+ try:
82
+ internetSettings = winreg.OpenKey(
83
+ winreg.HKEY_CURRENT_USER,
84
+ r"Software\Microsoft\Windows\CurrentVersion\Internet Settings",
85
+ )
86
+ # ProxyEnable could be REG_SZ or REG_DWORD, normalizing it
87
+ proxyEnable = int(winreg.QueryValueEx(internetSettings, "ProxyEnable")[0])
88
+ # ProxyOverride is almost always a string
89
+ proxyOverride = winreg.QueryValueEx(internetSettings, "ProxyOverride")[0]
90
+ except (OSError, ValueError):
91
+ return False
92
+ if not proxyEnable or not proxyOverride:
93
+ return False
94
+
95
+ # make a check value list from the registry entry: replace the
96
+ # '<local>' string by the localhost entry and the corresponding
97
+ # canonical entry.
98
+ proxyOverride = proxyOverride.split(";")
99
+ # now check if we match one of the registry values.
100
+ for test in proxyOverride:
101
+ if test == "<local>":
102
+ if "." not in host:
103
+ return True
104
+ test = test.replace(".", r"\.") # mask dots
105
+ test = test.replace("*", r".*") # change glob sequence
106
+ test = test.replace("?", r".") # change glob char
107
+ if re.match(test, host, re.I):
108
+ return True
109
+ return False
110
+
111
+ def proxy_bypass(host): # noqa
112
+ """Return True, if the host should be bypassed.
113
+
114
+ Checks proxy settings gathered from the environment, if specified,
115
+ or the registry.
116
+ """
117
+ if getproxies_environment():
118
+ return proxy_bypass_environment(host)
119
+ else:
120
+ return proxy_bypass_registry(host)
121
+
122
+
123
+ def dict_to_sequence(d):
124
+ """Returns an internal sequence dictionary update."""
125
+
126
+ if hasattr(d, "items"):
127
+ d = d.items()
128
+
129
+ return d
130
+
131
+
132
+ def super_len(o):
133
+ total_length = None
134
+ current_position = 0
135
+
136
+ if hasattr(o, "__len__"):
137
+ total_length = len(o)
138
+
139
+ elif hasattr(o, "len"):
140
+ total_length = o.len
141
+
142
+ elif hasattr(o, "fileno"):
143
+ try:
144
+ fileno = o.fileno()
145
+ except (io.UnsupportedOperation, AttributeError):
146
+ # AttributeError is a surprising exception, seeing as how we've just checked
147
+ # that `hasattr(o, 'fileno')`. It happens for objects obtained via
148
+ # `Tarfile.extractfile()`, per issue 5229.
149
+ pass
150
+ else:
151
+ total_length = os.fstat(fileno).st_size
152
+
153
+ # Having used fstat to determine the file length, we need to
154
+ # confirm that this file was opened up in binary mode.
155
+ if "b" not in o.mode:
156
+ warnings.warn(
157
+ (
158
+ "Requests has determined the content-length for this "
159
+ "request using the binary size of the file: however, the "
160
+ "file has been opened in text mode (i.e. without the 'b' "
161
+ "flag in the mode). This may lead to an incorrect "
162
+ "content-length. In Requests 3.0, support will be removed "
163
+ "for files in text mode."
164
+ ),
165
+ FileModeWarning,
166
+ )
167
+
168
+ if hasattr(o, "tell"):
169
+ try:
170
+ current_position = o.tell()
171
+ except OSError:
172
+ # This can happen in some weird situations, such as when the file
173
+ # is actually a special file descriptor like stdin. In this
174
+ # instance, we don't know what the length is, so set it to zero and
175
+ # let requests chunk it instead.
176
+ if total_length is not None:
177
+ current_position = total_length
178
+ else:
179
+ if hasattr(o, "seek") and total_length is None:
180
+ # StringIO and BytesIO have seek but no usable fileno
181
+ try:
182
+ # seek to end of file
183
+ o.seek(0, 2)
184
+ total_length = o.tell()
185
+
186
+ # seek back to current position to support
187
+ # partially read file-like objects
188
+ o.seek(current_position or 0)
189
+ except OSError:
190
+ total_length = 0
191
+
192
+ if total_length is None:
193
+ total_length = 0
194
+
195
+ return max(0, total_length - current_position)
196
+
197
+
198
+ def get_netrc_auth(url, raise_errors=False):
199
+ """Returns the Requests tuple auth for a given url from netrc."""
200
+
201
+ netrc_file = os.environ.get("NETRC")
202
+ if netrc_file is not None:
203
+ netrc_locations = (netrc_file,)
204
+ else:
205
+ netrc_locations = (f"~/{f}" for f in NETRC_FILES)
206
+
207
+ try:
208
+ from netrc import NetrcParseError, netrc
209
+
210
+ netrc_path = None
211
+
212
+ for f in netrc_locations:
213
+ try:
214
+ loc = os.path.expanduser(f)
215
+ except KeyError:
216
+ # os.path.expanduser can fail when $HOME is undefined and
217
+ # getpwuid fails. See https://bugs.python.org/issue20164 &
218
+ # https://github.com/psf/requests/issues/1846
219
+ return
220
+
221
+ if os.path.exists(loc):
222
+ netrc_path = loc
223
+ break
224
+
225
+ # Abort early if there isn't one.
226
+ if netrc_path is None:
227
+ return
228
+
229
+ ri = urlparse(url)
230
+
231
+ # Strip port numbers from netloc. This weird `if...encode`` dance is
232
+ # used for Python 3.2, which doesn't support unicode literals.
233
+ splitstr = b":"
234
+ if isinstance(url, str):
235
+ splitstr = splitstr.decode("ascii")
236
+ host = ri.netloc.split(splitstr)[0]
237
+
238
+ try:
239
+ _netrc = netrc(netrc_path).authenticators(host)
240
+ if _netrc:
241
+ # Return with login / password
242
+ login_i = 0 if _netrc[0] else 1
243
+ return (_netrc[login_i], _netrc[2])
244
+ except (NetrcParseError, OSError):
245
+ # If there was a parsing error or a permissions issue reading the file,
246
+ # we'll just skip netrc auth unless explicitly asked to raise errors.
247
+ if raise_errors:
248
+ raise
249
+
250
+ # App Engine hackiness.
251
+ except (ImportError, AttributeError):
252
+ pass
253
+
254
+
255
+ def guess_filename(obj):
256
+ """Tries to guess the filename of the given object."""
257
+ name = getattr(obj, "name", None)
258
+ if name and isinstance(name, basestring) and name[0] != "<" and name[-1] != ">":
259
+ return os.path.basename(name)
260
+
261
+
262
+ def extract_zipped_paths(path):
263
+ """Replace nonexistent paths that look like they refer to a member of a zip
264
+ archive with the location of an extracted copy of the target, or else
265
+ just return the provided path unchanged.
266
+ """
267
+ if os.path.exists(path):
268
+ # this is already a valid path, no need to do anything further
269
+ return path
270
+
271
+ # find the first valid part of the provided path and treat that as a zip archive
272
+ # assume the rest of the path is the name of a member in the archive
273
+ archive, member = os.path.split(path)
274
+ while archive and not os.path.exists(archive):
275
+ archive, prefix = os.path.split(archive)
276
+ if not prefix:
277
+ # If we don't check for an empty prefix after the split (in other words, archive remains unchanged after the split),
278
+ # we _can_ end up in an infinite loop on a rare corner case affecting a small number of users
279
+ break
280
+ member = "/".join([prefix, member])
281
+
282
+ if not zipfile.is_zipfile(archive):
283
+ return path
284
+
285
+ zip_file = zipfile.ZipFile(archive)
286
+ if member not in zip_file.namelist():
287
+ return path
288
+
289
+ # we have a valid zip archive and a valid member of that archive
290
+ tmp = tempfile.gettempdir()
291
+ extracted_path = os.path.join(tmp, member.split("/")[-1])
292
+ if not os.path.exists(extracted_path):
293
+ # use read + write to avoid the creating nested folders, we only want the file, avoids mkdir racing condition
294
+ with atomic_open(extracted_path) as file_handler:
295
+ file_handler.write(zip_file.read(member))
296
+ return extracted_path
297
+
298
+
299
+ @contextlib.contextmanager
300
+ def atomic_open(filename):
301
+ """Write a file to the disk in an atomic fashion"""
302
+ tmp_descriptor, tmp_name = tempfile.mkstemp(dir=os.path.dirname(filename))
303
+ try:
304
+ with os.fdopen(tmp_descriptor, "wb") as tmp_handler:
305
+ yield tmp_handler
306
+ os.replace(tmp_name, filename)
307
+ except BaseException:
308
+ os.remove(tmp_name)
309
+ raise
310
+
311
+
312
+ def from_key_val_list(value):
313
+ """Take an object and test to see if it can be represented as a
314
+ dictionary. Unless it can not be represented as such, return an
315
+ OrderedDict, e.g.,
316
+
317
+ ::
318
+
319
+ >>> from_key_val_list([('key', 'val')])
320
+ OrderedDict([('key', 'val')])
321
+ >>> from_key_val_list('string')
322
+ Traceback (most recent call last):
323
+ ...
324
+ ValueError: cannot encode objects that are not 2-tuples
325
+ >>> from_key_val_list({'key': 'val'})
326
+ OrderedDict([('key', 'val')])
327
+
328
+ :rtype: OrderedDict
329
+ """
330
+ if value is None:
331
+ return None
332
+
333
+ if isinstance(value, (str, bytes, bool, int)):
334
+ raise ValueError("cannot encode objects that are not 2-tuples")
335
+
336
+ return OrderedDict(value)
337
+
338
+
339
+ def to_key_val_list(value):
340
+ """Take an object and test to see if it can be represented as a
341
+ dictionary. If it can be, return a list of tuples, e.g.,
342
+
343
+ ::
344
+
345
+ >>> to_key_val_list([('key', 'val')])
346
+ [('key', 'val')]
347
+ >>> to_key_val_list({'key': 'val'})
348
+ [('key', 'val')]
349
+ >>> to_key_val_list('string')
350
+ Traceback (most recent call last):
351
+ ...
352
+ ValueError: cannot encode objects that are not 2-tuples
353
+
354
+ :rtype: list
355
+ """
356
+ if value is None:
357
+ return None
358
+
359
+ if isinstance(value, (str, bytes, bool, int)):
360
+ raise ValueError("cannot encode objects that are not 2-tuples")
361
+
362
+ if isinstance(value, Mapping):
363
+ value = value.items()
364
+
365
+ return list(value)
366
+
367
+
368
+ # From mitsuhiko/werkzeug (used with permission).
369
+ def parse_list_header(value):
370
+ """Parse lists as described by RFC 2068 Section 2.
371
+
372
+ In particular, parse comma-separated lists where the elements of
373
+ the list may include quoted-strings. A quoted-string could
374
+ contain a comma. A non-quoted string could have quotes in the
375
+ middle. Quotes are removed automatically after parsing.
376
+
377
+ It basically works like :func:`parse_set_header` just that items
378
+ may appear multiple times and case sensitivity is preserved.
379
+
380
+ The return value is a standard :class:`list`:
381
+
382
+ >>> parse_list_header('token, "quoted value"')
383
+ ['token', 'quoted value']
384
+
385
+ To create a header from the :class:`list` again, use the
386
+ :func:`dump_header` function.
387
+
388
+ :param value: a string with a list header.
389
+ :return: :class:`list`
390
+ :rtype: list
391
+ """
392
+ result = []
393
+ for item in _parse_list_header(value):
394
+ if item[:1] == item[-1:] == '"':
395
+ item = unquote_header_value(item[1:-1])
396
+ result.append(item)
397
+ return result
398
+
399
+
400
+ # From mitsuhiko/werkzeug (used with permission).
401
+ def parse_dict_header(value):
402
+ """Parse lists of key, value pairs as described by RFC 2068 Section 2 and
403
+ convert them into a python dict:
404
+
405
+ >>> d = parse_dict_header('foo="is a fish", bar="as well"')
406
+ >>> type(d) is dict
407
+ True
408
+ >>> sorted(d.items())
409
+ [('bar', 'as well'), ('foo', 'is a fish')]
410
+
411
+ If there is no value for a key it will be `None`:
412
+
413
+ >>> parse_dict_header('key_without_value')
414
+ {'key_without_value': None}
415
+
416
+ To create a header from the :class:`dict` again, use the
417
+ :func:`dump_header` function.
418
+
419
+ :param value: a string with a dict header.
420
+ :return: :class:`dict`
421
+ :rtype: dict
422
+ """
423
+ result = {}
424
+ for item in _parse_list_header(value):
425
+ if "=" not in item:
426
+ result[item] = None
427
+ continue
428
+ name, value = item.split("=", 1)
429
+ if value[:1] == value[-1:] == '"':
430
+ value = unquote_header_value(value[1:-1])
431
+ result[name] = value
432
+ return result
433
+
434
+
435
+ # From mitsuhiko/werkzeug (used with permission).
436
+ def unquote_header_value(value, is_filename=False):
437
+ r"""Unquotes a header value. (Reversal of :func:`quote_header_value`).
438
+ This does not use the real unquoting but what browsers are actually
439
+ using for quoting.
440
+
441
+ :param value: the header value to unquote.
442
+ :rtype: str
443
+ """
444
+ if value and value[0] == value[-1] == '"':
445
+ # this is not the real unquoting, but fixing this so that the
446
+ # RFC is met will result in bugs with internet explorer and
447
+ # probably some other browsers as well. IE for example is
448
+ # uploading files with "C:\foo\bar.txt" as filename
449
+ value = value[1:-1]
450
+
451
+ # if this is a filename and the starting characters look like
452
+ # a UNC path, then just return the value without quotes. Using the
453
+ # replace sequence below on a UNC path has the effect of turning
454
+ # the leading double slash into a single slash and then
455
+ # _fix_ie_filename() doesn't work correctly. See #458.
456
+ if not is_filename or value[:2] != "\\\\":
457
+ return value.replace("\\\\", "\\").replace('\\"', '"')
458
+ return value
459
+
460
+
461
+ def dict_from_cookiejar(cj):
462
+ """Returns a key/value dictionary from a CookieJar.
463
+
464
+ :param cj: CookieJar object to extract cookies from.
465
+ :rtype: dict
466
+ """
467
+
468
+ cookie_dict = {}
469
+
470
+ for cookie in cj:
471
+ cookie_dict[cookie.name] = cookie.value
472
+
473
+ return cookie_dict
474
+
475
+
476
+ def add_dict_to_cookiejar(cj, cookie_dict):
477
+ """Returns a CookieJar from a key/value dictionary.
478
+
479
+ :param cj: CookieJar to insert cookies into.
480
+ :param cookie_dict: Dict of key/values to insert into CookieJar.
481
+ :rtype: CookieJar
482
+ """
483
+
484
+ return cookiejar_from_dict(cookie_dict, cj)
485
+
486
+
487
+ def get_encodings_from_content(content):
488
+ """Returns encodings from given content string.
489
+
490
+ :param content: bytestring to extract encodings from.
491
+ """
492
+ warnings.warn(
493
+ (
494
+ "In requests 3.0, get_encodings_from_content will be removed. For "
495
+ "more information, please see the discussion on issue #2266. (This"
496
+ " warning should only appear once.)"
497
+ ),
498
+ DeprecationWarning,
499
+ )
500
+
501
+ charset_re = re.compile(r'<meta.*?charset=["\']*(.+?)["\'>]', flags=re.I)
502
+ pragma_re = re.compile(r'<meta.*?content=["\']*;?charset=(.+?)["\'>]', flags=re.I)
503
+ xml_re = re.compile(r'^<\?xml.*?encoding=["\']*(.+?)["\'>]')
504
+
505
+ return (
506
+ charset_re.findall(content)
507
+ + pragma_re.findall(content)
508
+ + xml_re.findall(content)
509
+ )
510
+
511
+
512
+ def _parse_content_type_header(header):
513
+ """Returns content type and parameters from given header
514
+
515
+ :param header: string
516
+ :return: tuple containing content type and dictionary of
517
+ parameters
518
+ """
519
+
520
+ tokens = header.split(";")
521
+ content_type, params = tokens[0].strip(), tokens[1:]
522
+ params_dict = {}
523
+ items_to_strip = "\"' "
524
+
525
+ for param in params:
526
+ param = param.strip()
527
+ if param:
528
+ key, value = param, True
529
+ index_of_equals = param.find("=")
530
+ if index_of_equals != -1:
531
+ key = param[:index_of_equals].strip(items_to_strip)
532
+ value = param[index_of_equals + 1 :].strip(items_to_strip)
533
+ params_dict[key.lower()] = value
534
+ return content_type, params_dict
535
+
536
+
537
+ def get_encoding_from_headers(headers):
538
+ """Returns encodings from given HTTP Header Dict.
539
+
540
+ :param headers: dictionary to extract encoding from.
541
+ :rtype: str
542
+ """
543
+
544
+ content_type = headers.get("content-type")
545
+
546
+ if not content_type:
547
+ return None
548
+
549
+ content_type, params = _parse_content_type_header(content_type)
550
+
551
+ if "charset" in params:
552
+ return params["charset"].strip("'\"")
553
+
554
+ if "text" in content_type:
555
+ return "ISO-8859-1"
556
+
557
+ if "application/json" in content_type:
558
+ # Assume UTF-8 based on RFC 4627: https://www.ietf.org/rfc/rfc4627.txt since the charset was unset
559
+ return "utf-8"
560
+
561
+
562
+ def stream_decode_response_unicode(iterator, r):
563
+ """Stream decodes an iterator."""
564
+
565
+ if r.encoding is None:
566
+ yield from iterator
567
+ return
568
+
569
+ decoder = codecs.getincrementaldecoder(r.encoding)(errors="replace")
570
+ for chunk in iterator:
571
+ rv = decoder.decode(chunk)
572
+ if rv:
573
+ yield rv
574
+ rv = decoder.decode(b"", final=True)
575
+ if rv:
576
+ yield rv
577
+
578
+
579
+ def iter_slices(string, slice_length):
580
+ """Iterate over slices of a string."""
581
+ pos = 0
582
+ if slice_length is None or slice_length <= 0:
583
+ slice_length = len(string)
584
+ while pos < len(string):
585
+ yield string[pos : pos + slice_length]
586
+ pos += slice_length
587
+
588
+
589
+ def get_unicode_from_response(r):
590
+ """Returns the requested content back in unicode.
591
+
592
+ :param r: Response object to get unicode content from.
593
+
594
+ Tried:
595
+
596
+ 1. charset from content-type
597
+ 2. fall back and replace all unicode characters
598
+
599
+ :rtype: str
600
+ """
601
+ warnings.warn(
602
+ (
603
+ "In requests 3.0, get_unicode_from_response will be removed. For "
604
+ "more information, please see the discussion on issue #2266. (This"
605
+ " warning should only appear once.)"
606
+ ),
607
+ DeprecationWarning,
608
+ )
609
+
610
+ tried_encodings = []
611
+
612
+ # Try charset from content-type
613
+ encoding = get_encoding_from_headers(r.headers)
614
+
615
+ if encoding:
616
+ try:
617
+ return str(r.content, encoding)
618
+ except UnicodeError:
619
+ tried_encodings.append(encoding)
620
+
621
+ # Fall back:
622
+ try:
623
+ return str(r.content, encoding, errors="replace")
624
+ except TypeError:
625
+ return r.content
626
+
627
+
628
+ # The unreserved URI characters (RFC 3986)
629
+ UNRESERVED_SET = frozenset(
630
+ "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz" + "0123456789-._~"
631
+ )
632
+
633
+
634
+ def unquote_unreserved(uri):
635
+ """Un-escape any percent-escape sequences in a URI that are unreserved
636
+ characters. This leaves all reserved, illegal and non-ASCII bytes encoded.
637
+
638
+ :rtype: str
639
+ """
640
+ parts = uri.split("%")
641
+ for i in range(1, len(parts)):
642
+ h = parts[i][0:2]
643
+ if len(h) == 2 and h.isalnum():
644
+ try:
645
+ c = chr(int(h, 16))
646
+ except ValueError:
647
+ raise InvalidURL(f"Invalid percent-escape sequence: '{h}'")
648
+
649
+ if c in UNRESERVED_SET:
650
+ parts[i] = c + parts[i][2:]
651
+ else:
652
+ parts[i] = f"%{parts[i]}"
653
+ else:
654
+ parts[i] = f"%{parts[i]}"
655
+ return "".join(parts)
656
+
657
+
658
+ def requote_uri(uri):
659
+ """Re-quote the given URI.
660
+
661
+ This function passes the given URI through an unquote/quote cycle to
662
+ ensure that it is fully and consistently quoted.
663
+
664
+ :rtype: str
665
+ """
666
+ safe_with_percent = "!#$%&'()*+,/:;=?@[]~"
667
+ safe_without_percent = "!#$&'()*+,/:;=?@[]~"
668
+ try:
669
+ # Unquote only the unreserved characters
670
+ # Then quote only illegal characters (do not quote reserved,
671
+ # unreserved, or '%')
672
+ return quote(unquote_unreserved(uri), safe=safe_with_percent)
673
+ except InvalidURL:
674
+ # We couldn't unquote the given URI, so let's try quoting it, but
675
+ # there may be unquoted '%'s in the URI. We need to make sure they're
676
+ # properly quoted so they do not cause issues elsewhere.
677
+ return quote(uri, safe=safe_without_percent)
678
+
679
+
680
+ def address_in_network(ip, net):
681
+ """This function allows you to check if an IP belongs to a network subnet
682
+
683
+ Example: returns True if ip = 192.168.1.1 and net = 192.168.1.0/24
684
+ returns False if ip = 192.168.1.1 and net = 192.168.100.0/24
685
+
686
+ :rtype: bool
687
+ """
688
+ ipaddr = struct.unpack("=L", socket.inet_aton(ip))[0]
689
+ netaddr, bits = net.split("/")
690
+ netmask = struct.unpack("=L", socket.inet_aton(dotted_netmask(int(bits))))[0]
691
+ network = struct.unpack("=L", socket.inet_aton(netaddr))[0] & netmask
692
+ return (ipaddr & netmask) == (network & netmask)
693
+
694
+
695
+ def dotted_netmask(mask):
696
+ """Converts mask from /xx format to xxx.xxx.xxx.xxx
697
+
698
+ Example: if mask is 24 function returns 255.255.255.0
699
+
700
+ :rtype: str
701
+ """
702
+ bits = 0xFFFFFFFF ^ (1 << 32 - mask) - 1
703
+ return socket.inet_ntoa(struct.pack(">I", bits))
704
+
705
+
706
+ def is_ipv4_address(string_ip):
707
+ """
708
+ :rtype: bool
709
+ """
710
+ try:
711
+ socket.inet_aton(string_ip)
712
+ except OSError:
713
+ return False
714
+ return True
715
+
716
+
717
+ def is_valid_cidr(string_network):
718
+ """
719
+ Very simple check of the cidr format in no_proxy variable.
720
+
721
+ :rtype: bool
722
+ """
723
+ if string_network.count("/") == 1:
724
+ try:
725
+ mask = int(string_network.split("/")[1])
726
+ except ValueError:
727
+ return False
728
+
729
+ if mask < 1 or mask > 32:
730
+ return False
731
+
732
+ try:
733
+ socket.inet_aton(string_network.split("/")[0])
734
+ except OSError:
735
+ return False
736
+ else:
737
+ return False
738
+ return True
739
+
740
+
741
+ @contextlib.contextmanager
742
+ def set_environ(env_name, value):
743
+ """Set the environment variable 'env_name' to 'value'
744
+
745
+ Save previous value, yield, and then restore the previous value stored in
746
+ the environment variable 'env_name'.
747
+
748
+ If 'value' is None, do nothing"""
749
+ value_changed = value is not None
750
+ if value_changed:
751
+ old_value = os.environ.get(env_name)
752
+ os.environ[env_name] = value
753
+ try:
754
+ yield
755
+ finally:
756
+ if value_changed:
757
+ if old_value is None:
758
+ del os.environ[env_name]
759
+ else:
760
+ os.environ[env_name] = old_value
761
+
762
+
763
+ def should_bypass_proxies(url, no_proxy):
764
+ """
765
+ Returns whether we should bypass proxies or not.
766
+
767
+ :rtype: bool
768
+ """
769
+ # Prioritize lowercase environment variables over uppercase
770
+ # to keep a consistent behaviour with other http projects (curl, wget).
771
+ def get_proxy(key):
772
+ return os.environ.get(key) or os.environ.get(key.upper())
773
+
774
+ # First check whether no_proxy is defined. If it is, check that the URL
775
+ # we're getting isn't in the no_proxy list.
776
+ no_proxy_arg = no_proxy
777
+ if no_proxy is None:
778
+ no_proxy = get_proxy("no_proxy")
779
+ parsed = urlparse(url)
780
+
781
+ if parsed.hostname is None:
782
+ # URLs don't always have hostnames, e.g. file:/// urls.
783
+ return True
784
+
785
+ if no_proxy:
786
+ # We need to check whether we match here. We need to see if we match
787
+ # the end of the hostname, both with and without the port.
788
+ no_proxy = (host for host in no_proxy.replace(" ", "").split(",") if host)
789
+
790
+ if is_ipv4_address(parsed.hostname):
791
+ for proxy_ip in no_proxy:
792
+ if is_valid_cidr(proxy_ip):
793
+ if address_in_network(parsed.hostname, proxy_ip):
794
+ return True
795
+ elif parsed.hostname == proxy_ip:
796
+ # If no_proxy ip was defined in plain IP notation instead of cidr notation &
797
+ # matches the IP of the index
798
+ return True
799
+ else:
800
+ host_with_port = parsed.hostname
801
+ if parsed.port:
802
+ host_with_port += f":{parsed.port}"
803
+
804
+ for host in no_proxy:
805
+ if parsed.hostname.endswith(host) or host_with_port.endswith(host):
806
+ # The URL does match something in no_proxy, so we don't want
807
+ # to apply the proxies on this URL.
808
+ return True
809
+
810
+ with set_environ("no_proxy", no_proxy_arg):
811
+ # parsed.hostname can be `None` in cases such as a file URI.
812
+ try:
813
+ bypass = proxy_bypass(parsed.hostname)
814
+ except (TypeError, socket.gaierror):
815
+ bypass = False
816
+
817
+ if bypass:
818
+ return True
819
+
820
+ return False
821
+
822
+
823
+ def get_environ_proxies(url, no_proxy=None):
824
+ """
825
+ Return a dict of environment proxies.
826
+
827
+ :rtype: dict
828
+ """
829
+ if should_bypass_proxies(url, no_proxy=no_proxy):
830
+ return {}
831
+ else:
832
+ return getproxies()
833
+
834
+
835
+ def select_proxy(url, proxies):
836
+ """Select a proxy for the url, if applicable.
837
+
838
+ :param url: The url being for the request
839
+ :param proxies: A dictionary of schemes or schemes and hosts to proxy URLs
840
+ """
841
+ proxies = proxies or {}
842
+ urlparts = urlparse(url)
843
+ if urlparts.hostname is None:
844
+ return proxies.get(urlparts.scheme, proxies.get("all"))
845
+
846
+ proxy_keys = [
847
+ urlparts.scheme + "://" + urlparts.hostname,
848
+ urlparts.scheme,
849
+ "all://" + urlparts.hostname,
850
+ "all",
851
+ ]
852
+ proxy = None
853
+ for proxy_key in proxy_keys:
854
+ if proxy_key in proxies:
855
+ proxy = proxies[proxy_key]
856
+ break
857
+
858
+ return proxy
859
+
860
+
861
+ def resolve_proxies(request, proxies, trust_env=True):
862
+ """This method takes proxy information from a request and configuration
863
+ input to resolve a mapping of target proxies. This will consider settings
864
+ such a NO_PROXY to strip proxy configurations.
865
+
866
+ :param request: Request or PreparedRequest
867
+ :param proxies: A dictionary of schemes or schemes and hosts to proxy URLs
868
+ :param trust_env: Boolean declaring whether to trust environment configs
869
+
870
+ :rtype: dict
871
+ """
872
+ proxies = proxies if proxies is not None else {}
873
+ url = request.url
874
+ scheme = urlparse(url).scheme
875
+ no_proxy = proxies.get("no_proxy")
876
+ new_proxies = proxies.copy()
877
+
878
+ if trust_env and not should_bypass_proxies(url, no_proxy=no_proxy):
879
+ environ_proxies = get_environ_proxies(url, no_proxy=no_proxy)
880
+
881
+ proxy = environ_proxies.get(scheme, environ_proxies.get("all"))
882
+
883
+ if proxy:
884
+ new_proxies.setdefault(scheme, proxy)
885
+ return new_proxies
886
+
887
+
888
+ def default_user_agent(name="python-requests"):
889
+ """
890
+ Return a string representing the default user agent.
891
+
892
+ :rtype: str
893
+ """
894
+ return f"{name}/{__version__}"
895
+
896
+
897
+ def default_headers():
898
+ """
899
+ :rtype: requests.structures.CaseInsensitiveDict
900
+ """
901
+ return CaseInsensitiveDict(
902
+ {
903
+ "User-Agent": default_user_agent(),
904
+ "Accept-Encoding": DEFAULT_ACCEPT_ENCODING,
905
+ "Accept": "*/*",
906
+ "Connection": "keep-alive",
907
+ }
908
+ )
909
+
910
+
911
+ def parse_header_links(value):
912
+ """Return a list of parsed link headers proxies.
913
+
914
+ i.e. Link: <http:/.../front.jpeg>; rel=front; type="image/jpeg",<http://.../back.jpeg>; rel=back;type="image/jpeg"
915
+
916
+ :rtype: list
917
+ """
918
+
919
+ links = []
920
+
921
+ replace_chars = " '\""
922
+
923
+ value = value.strip(replace_chars)
924
+ if not value:
925
+ return links
926
+
927
+ for val in re.split(", *<", value):
928
+ try:
929
+ url, params = val.split(";", 1)
930
+ except ValueError:
931
+ url, params = val, ""
932
+
933
+ link = {"url": url.strip("<> '\"")}
934
+
935
+ for param in params.split(";"):
936
+ try:
937
+ key, value = param.split("=")
938
+ except ValueError:
939
+ break
940
+
941
+ link[key.strip(replace_chars)] = value.strip(replace_chars)
942
+
943
+ links.append(link)
944
+
945
+ return links
946
+
947
+
948
+ # Null bytes; no need to recreate these on each call to guess_json_utf
949
+ _null = "\x00".encode("ascii") # encoding to ASCII for Python 3
950
+ _null2 = _null * 2
951
+ _null3 = _null * 3
952
+
953
+
954
+ def guess_json_utf(data):
955
+ """
956
+ :rtype: str
957
+ """
958
+ # JSON always starts with two ASCII characters, so detection is as
959
+ # easy as counting the nulls and from their location and count
960
+ # determine the encoding. Also detect a BOM, if present.
961
+ sample = data[:4]
962
+ if sample in (codecs.BOM_UTF32_LE, codecs.BOM_UTF32_BE):
963
+ return "utf-32" # BOM included
964
+ if sample[:3] == codecs.BOM_UTF8:
965
+ return "utf-8-sig" # BOM included, MS style (discouraged)
966
+ if sample[:2] in (codecs.BOM_UTF16_LE, codecs.BOM_UTF16_BE):
967
+ return "utf-16" # BOM included
968
+ nullcount = sample.count(_null)
969
+ if nullcount == 0:
970
+ return "utf-8"
971
+ if nullcount == 2:
972
+ if sample[::2] == _null2: # 1st and 3rd are null
973
+ return "utf-16-be"
974
+ if sample[1::2] == _null2: # 2nd and 4th are null
975
+ return "utf-16-le"
976
+ # Did not detect 2 valid UTF-16 ascii-range characters
977
+ if nullcount == 3:
978
+ if sample[:3] == _null3:
979
+ return "utf-32-be"
980
+ if sample[1:] == _null3:
981
+ return "utf-32-le"
982
+ # Did not detect a valid UTF-32 ascii-range character
983
+ return None
984
+
985
+
986
+ def prepend_scheme_if_needed(url, new_scheme):
987
+ """Given a URL that may or may not have a scheme, prepend the given scheme.
988
+ Does not replace a present scheme with the one provided as an argument.
989
+
990
+ :rtype: str
991
+ """
992
+ parsed = parse_url(url)
993
+ scheme, auth, host, port, path, query, fragment = parsed
994
+
995
+ # A defect in urlparse determines that there isn't a netloc present in some
996
+ # urls. We previously assumed parsing was overly cautious, and swapped the
997
+ # netloc and path. Due to a lack of tests on the original defect, this is
998
+ # maintained with parse_url for backwards compatibility.
999
+ netloc = parsed.netloc
1000
+ if not netloc:
1001
+ netloc, path = path, netloc
1002
+
1003
+ if auth:
1004
+ # parse_url doesn't provide the netloc with auth
1005
+ # so we'll add it ourselves.
1006
+ netloc = "@".join([auth, netloc])
1007
+ if scheme is None:
1008
+ scheme = new_scheme
1009
+ if path is None:
1010
+ path = ""
1011
+
1012
+ return urlunparse((scheme, netloc, path, "", query, fragment))
1013
+
1014
+
1015
+ def get_auth_from_url(url):
1016
+ """Given a url with authentication components, extract them into a tuple of
1017
+ username,password.
1018
+
1019
+ :rtype: (str,str)
1020
+ """
1021
+ parsed = urlparse(url)
1022
+
1023
+ try:
1024
+ auth = (unquote(parsed.username), unquote(parsed.password))
1025
+ except (AttributeError, TypeError):
1026
+ auth = ("", "")
1027
+
1028
+ return auth
1029
+
1030
+
1031
+ def check_header_validity(header):
1032
+ """Verifies that header parts don't contain leading whitespace
1033
+ reserved characters, or return characters.
1034
+
1035
+ :param header: tuple, in the format (name, value).
1036
+ """
1037
+ name, value = header
1038
+ _validate_header_part(header, name, 0)
1039
+ _validate_header_part(header, value, 1)
1040
+
1041
+
1042
+ def _validate_header_part(header, header_part, header_validator_index):
1043
+ if isinstance(header_part, str):
1044
+ validator = _HEADER_VALIDATORS_STR[header_validator_index]
1045
+ elif isinstance(header_part, bytes):
1046
+ validator = _HEADER_VALIDATORS_BYTE[header_validator_index]
1047
+ else:
1048
+ raise InvalidHeader(
1049
+ f"Header part ({header_part!r}) from {header} "
1050
+ f"must be of type str or bytes, not {type(header_part)}"
1051
+ )
1052
+
1053
+ if not validator.match(header_part):
1054
+ header_kind = "name" if header_validator_index == 0 else "value"
1055
+ raise InvalidHeader(
1056
+ f"Invalid leading whitespace, reserved character(s), or return"
1057
+ f"character(s) in header {header_kind}: {header_part!r}"
1058
+ )
1059
+
1060
+
1061
+ def urldefragauth(url):
1062
+ """
1063
+ Given a url remove the fragment and the authentication part.
1064
+
1065
+ :rtype: str
1066
+ """
1067
+ scheme, netloc, path, params, query, fragment = urlparse(url)
1068
+
1069
+ # see func:`prepend_scheme_if_needed`
1070
+ if not netloc:
1071
+ netloc, path = path, netloc
1072
+
1073
+ netloc = netloc.rsplit("@", 1)[-1]
1074
+
1075
+ return urlunparse((scheme, netloc, path, params, query, ""))
1076
+
1077
+
1078
+ def rewind_body(prepared_request):
1079
+ """Move file pointer back to its recorded starting position
1080
+ so it can be read again on redirect.
1081
+ """
1082
+ body_seek = getattr(prepared_request.body, "seek", None)
1083
+ if body_seek is not None and isinstance(
1084
+ prepared_request._body_position, integer_types
1085
+ ):
1086
+ try:
1087
+ body_seek(prepared_request._body_position)
1088
+ except OSError:
1089
+ raise UnrewindableBodyError(
1090
+ "An error occurred when rewinding request body for redirect."
1091
+ )
1092
+ else:
1093
+ raise UnrewindableBodyError("Unable to rewind request body for redirect.")