webull-openapi-python-sdk 1.0.0__py3-none-any.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 (295) hide show
  1. samples/__init__.py +1 -0
  2. samples/data/__init__.py +1 -0
  3. samples/data/data_client.py +57 -0
  4. samples/data/data_streaming_client.py +86 -0
  5. samples/data/data_streaming_client_async.py +101 -0
  6. samples/trade/__init__.py +0 -0
  7. samples/trade/trade_client.py +163 -0
  8. samples/trade/trade_client_v2.py +181 -0
  9. samples/trade/trade_event_client.py +47 -0
  10. webull/__init__.py +1 -0
  11. webull/core/__init__.py +12 -0
  12. webull/core/auth/__init__.py +0 -0
  13. webull/core/auth/algorithm/__init__.py +0 -0
  14. webull/core/auth/algorithm/sha_hmac1.py +65 -0
  15. webull/core/auth/algorithm/sha_hmac256.py +75 -0
  16. webull/core/auth/composer/__init__.py +0 -0
  17. webull/core/auth/composer/default_signature_composer.py +125 -0
  18. webull/core/auth/credentials.py +46 -0
  19. webull/core/auth/signers/__init__.py +0 -0
  20. webull/core/auth/signers/app_key_signer.py +72 -0
  21. webull/core/auth/signers/signer.py +48 -0
  22. webull/core/auth/signers/signer_factory.py +58 -0
  23. webull/core/cache/__init__.py +225 -0
  24. webull/core/client.py +410 -0
  25. webull/core/common/__init__.py +0 -0
  26. webull/core/common/api_type.py +19 -0
  27. webull/core/common/easy_enum.py +35 -0
  28. webull/core/common/region.py +7 -0
  29. webull/core/compat.py +85 -0
  30. webull/core/context/__init__.py +0 -0
  31. webull/core/context/request_context_holder.py +33 -0
  32. webull/core/data/endpoints.json +22 -0
  33. webull/core/data/retry_config.json +15 -0
  34. webull/core/endpoint/__init__.py +8 -0
  35. webull/core/endpoint/chained_endpoint_resolver.py +57 -0
  36. webull/core/endpoint/default_endpoint_resolver.py +60 -0
  37. webull/core/endpoint/local_config_regional_endpoint_resolver.py +77 -0
  38. webull/core/endpoint/resolver_endpoint_request.py +46 -0
  39. webull/core/endpoint/user_customized_endpoint_resolver.py +55 -0
  40. webull/core/exception/__init__.py +0 -0
  41. webull/core/exception/error_code.py +23 -0
  42. webull/core/exception/error_msg.py +21 -0
  43. webull/core/exception/exceptions.py +53 -0
  44. webull/core/headers.py +57 -0
  45. webull/core/http/__init__.py +0 -0
  46. webull/core/http/initializer/__init__.py +0 -0
  47. webull/core/http/initializer/client_initializer.py +79 -0
  48. webull/core/http/initializer/token/__init__.py +0 -0
  49. webull/core/http/initializer/token/bean/__init__.py +0 -0
  50. webull/core/http/initializer/token/bean/access_token.py +40 -0
  51. webull/core/http/initializer/token/bean/check_token_request.py +44 -0
  52. webull/core/http/initializer/token/bean/create_token_request.py +45 -0
  53. webull/core/http/initializer/token/bean/refresh_token_request.py +44 -0
  54. webull/core/http/initializer/token/token_manager.py +208 -0
  55. webull/core/http/initializer/token/token_operation.py +72 -0
  56. webull/core/http/method_type.py +43 -0
  57. webull/core/http/protocol_type.py +43 -0
  58. webull/core/http/request.py +121 -0
  59. webull/core/http/response.py +166 -0
  60. webull/core/request.py +278 -0
  61. webull/core/retry/__init__.py +0 -0
  62. webull/core/retry/backoff_strategy.py +102 -0
  63. webull/core/retry/retry_condition.py +214 -0
  64. webull/core/retry/retry_policy.py +63 -0
  65. webull/core/retry/retry_policy_context.py +51 -0
  66. webull/core/utils/__init__.py +0 -0
  67. webull/core/utils/common.py +62 -0
  68. webull/core/utils/data.py +25 -0
  69. webull/core/utils/desensitize.py +33 -0
  70. webull/core/utils/validation.py +49 -0
  71. webull/core/vendored/__init__.py +0 -0
  72. webull/core/vendored/requests/__init__.py +94 -0
  73. webull/core/vendored/requests/__version__.py +28 -0
  74. webull/core/vendored/requests/_internal_utils.py +56 -0
  75. webull/core/vendored/requests/adapters.py +539 -0
  76. webull/core/vendored/requests/api.py +166 -0
  77. webull/core/vendored/requests/auth.py +307 -0
  78. webull/core/vendored/requests/certs.py +34 -0
  79. webull/core/vendored/requests/compat.py +85 -0
  80. webull/core/vendored/requests/cookies.py +555 -0
  81. webull/core/vendored/requests/exceptions.py +136 -0
  82. webull/core/vendored/requests/help.py +134 -0
  83. webull/core/vendored/requests/hooks.py +48 -0
  84. webull/core/vendored/requests/models.py +960 -0
  85. webull/core/vendored/requests/packages/__init__.py +17 -0
  86. webull/core/vendored/requests/packages/certifi/__init__.py +17 -0
  87. webull/core/vendored/requests/packages/certifi/__main__.py +16 -0
  88. webull/core/vendored/requests/packages/certifi/cacert.pem +4433 -0
  89. webull/core/vendored/requests/packages/certifi/core.py +51 -0
  90. webull/core/vendored/requests/packages/chardet/__init__.py +53 -0
  91. webull/core/vendored/requests/packages/chardet/big5freq.py +400 -0
  92. webull/core/vendored/requests/packages/chardet/big5prober.py +61 -0
  93. webull/core/vendored/requests/packages/chardet/chardistribution.py +247 -0
  94. webull/core/vendored/requests/packages/chardet/charsetgroupprober.py +120 -0
  95. webull/core/vendored/requests/packages/chardet/charsetprober.py +159 -0
  96. webull/core/vendored/requests/packages/chardet/cli/__init__.py +1 -0
  97. webull/core/vendored/requests/packages/chardet/cli/chardetect.py +99 -0
  98. webull/core/vendored/requests/packages/chardet/codingstatemachine.py +102 -0
  99. webull/core/vendored/requests/packages/chardet/compat.py +48 -0
  100. webull/core/vendored/requests/packages/chardet/cp949prober.py +63 -0
  101. webull/core/vendored/requests/packages/chardet/enums.py +90 -0
  102. webull/core/vendored/requests/packages/chardet/escprober.py +115 -0
  103. webull/core/vendored/requests/packages/chardet/escsm.py +260 -0
  104. webull/core/vendored/requests/packages/chardet/eucjpprober.py +106 -0
  105. webull/core/vendored/requests/packages/chardet/euckrfreq.py +209 -0
  106. webull/core/vendored/requests/packages/chardet/euckrprober.py +61 -0
  107. webull/core/vendored/requests/packages/chardet/euctwfreq.py +401 -0
  108. webull/core/vendored/requests/packages/chardet/euctwprober.py +60 -0
  109. webull/core/vendored/requests/packages/chardet/gb2312freq.py +297 -0
  110. webull/core/vendored/requests/packages/chardet/gb2312prober.py +60 -0
  111. webull/core/vendored/requests/packages/chardet/hebrewprober.py +306 -0
  112. webull/core/vendored/requests/packages/chardet/jisfreq.py +339 -0
  113. webull/core/vendored/requests/packages/chardet/jpcntx.py +247 -0
  114. webull/core/vendored/requests/packages/chardet/langbulgarianmodel.py +242 -0
  115. webull/core/vendored/requests/packages/chardet/langcyrillicmodel.py +347 -0
  116. webull/core/vendored/requests/packages/chardet/langgreekmodel.py +239 -0
  117. webull/core/vendored/requests/packages/chardet/langhebrewmodel.py +214 -0
  118. webull/core/vendored/requests/packages/chardet/langhungarianmodel.py +239 -0
  119. webull/core/vendored/requests/packages/chardet/langthaimodel.py +213 -0
  120. webull/core/vendored/requests/packages/chardet/langturkishmodel.py +207 -0
  121. webull/core/vendored/requests/packages/chardet/latin1prober.py +159 -0
  122. webull/core/vendored/requests/packages/chardet/mbcharsetprober.py +105 -0
  123. webull/core/vendored/requests/packages/chardet/mbcsgroupprober.py +68 -0
  124. webull/core/vendored/requests/packages/chardet/mbcssm.py +586 -0
  125. webull/core/vendored/requests/packages/chardet/sbcharsetprober.py +146 -0
  126. webull/core/vendored/requests/packages/chardet/sbcsgroupprober.py +87 -0
  127. webull/core/vendored/requests/packages/chardet/sjisprober.py +106 -0
  128. webull/core/vendored/requests/packages/chardet/universaldetector.py +300 -0
  129. webull/core/vendored/requests/packages/chardet/utf8prober.py +96 -0
  130. webull/core/vendored/requests/packages/chardet/version.py +23 -0
  131. webull/core/vendored/requests/packages/urllib3/__init__.py +114 -0
  132. webull/core/vendored/requests/packages/urllib3/_collections.py +346 -0
  133. webull/core/vendored/requests/packages/urllib3/connection.py +405 -0
  134. webull/core/vendored/requests/packages/urllib3/connectionpool.py +910 -0
  135. webull/core/vendored/requests/packages/urllib3/contrib/__init__.py +0 -0
  136. webull/core/vendored/requests/packages/urllib3/contrib/_appengine_environ.py +44 -0
  137. webull/core/vendored/requests/packages/urllib3/contrib/_securetransport/__init__.py +0 -0
  138. webull/core/vendored/requests/packages/urllib3/contrib/_securetransport/bindings.py +607 -0
  139. webull/core/vendored/requests/packages/urllib3/contrib/_securetransport/low_level.py +360 -0
  140. webull/core/vendored/requests/packages/urllib3/contrib/appengine.py +303 -0
  141. webull/core/vendored/requests/packages/urllib3/contrib/ntlmpool.py +125 -0
  142. webull/core/vendored/requests/packages/urllib3/contrib/pyopenssl.py +484 -0
  143. webull/core/vendored/requests/packages/urllib3/contrib/securetransport.py +818 -0
  144. webull/core/vendored/requests/packages/urllib3/contrib/socks.py +206 -0
  145. webull/core/vendored/requests/packages/urllib3/exceptions.py +260 -0
  146. webull/core/vendored/requests/packages/urllib3/fields.py +192 -0
  147. webull/core/vendored/requests/packages/urllib3/filepost.py +112 -0
  148. webull/core/vendored/requests/packages/urllib3/packages/__init__.py +19 -0
  149. webull/core/vendored/requests/packages/urllib3/packages/backports/__init__.py +0 -0
  150. webull/core/vendored/requests/packages/urllib3/packages/backports/makefile.py +67 -0
  151. webull/core/vendored/requests/packages/urllib3/packages/ordered_dict.py +273 -0
  152. webull/core/vendored/requests/packages/urllib3/packages/six.py +882 -0
  153. webull/core/vendored/requests/packages/urllib3/packages/socks.py +887 -0
  154. webull/core/vendored/requests/packages/urllib3/packages/ssl_match_hostname/__init__.py +19 -0
  155. webull/core/vendored/requests/packages/urllib3/packages/ssl_match_hostname/_implementation.py +170 -0
  156. webull/core/vendored/requests/packages/urllib3/poolmanager.py +467 -0
  157. webull/core/vendored/requests/packages/urllib3/request.py +164 -0
  158. webull/core/vendored/requests/packages/urllib3/response.py +721 -0
  159. webull/core/vendored/requests/packages/urllib3/util/__init__.py +68 -0
  160. webull/core/vendored/requests/packages/urllib3/util/connection.py +148 -0
  161. webull/core/vendored/requests/packages/urllib3/util/queue.py +35 -0
  162. webull/core/vendored/requests/packages/urllib3/util/request.py +132 -0
  163. webull/core/vendored/requests/packages/urllib3/util/response.py +101 -0
  164. webull/core/vendored/requests/packages/urllib3/util/retry.py +426 -0
  165. webull/core/vendored/requests/packages/urllib3/util/selectors.py +601 -0
  166. webull/core/vendored/requests/packages/urllib3/util/ssl_.py +396 -0
  167. webull/core/vendored/requests/packages/urllib3/util/timeout.py +256 -0
  168. webull/core/vendored/requests/packages/urllib3/util/url.py +252 -0
  169. webull/core/vendored/requests/packages/urllib3/util/wait.py +164 -0
  170. webull/core/vendored/requests/packages.py +28 -0
  171. webull/core/vendored/requests/sessions.py +750 -0
  172. webull/core/vendored/requests/status_codes.py +105 -0
  173. webull/core/vendored/requests/structures.py +119 -0
  174. webull/core/vendored/requests/utils.py +916 -0
  175. webull/core/vendored/six.py +905 -0
  176. webull/data/__init__.py +3 -0
  177. webull/data/common/__init__.py +0 -0
  178. webull/data/common/category.py +26 -0
  179. webull/data/common/connect_ack.py +29 -0
  180. webull/data/common/direction.py +25 -0
  181. webull/data/common/exchange_code.py +33 -0
  182. webull/data/common/exercise_style.py +22 -0
  183. webull/data/common/expiration_cycle.py +26 -0
  184. webull/data/common/instrument_status.py +23 -0
  185. webull/data/common/option_type.py +20 -0
  186. webull/data/common/subscribe_type.py +22 -0
  187. webull/data/common/timespan.py +29 -0
  188. webull/data/data_client.py +35 -0
  189. webull/data/data_streaming_client.py +89 -0
  190. webull/data/internal/__init__.py +0 -0
  191. webull/data/internal/default_retry_policy.py +84 -0
  192. webull/data/internal/exceptions.py +60 -0
  193. webull/data/internal/quotes_client.py +314 -0
  194. webull/data/internal/quotes_decoder.py +40 -0
  195. webull/data/internal/quotes_payload_decoder.py +35 -0
  196. webull/data/internal/quotes_topic.py +36 -0
  197. webull/data/quotes/__init__.py +0 -0
  198. webull/data/quotes/instrument.py +33 -0
  199. webull/data/quotes/market_data.py +187 -0
  200. webull/data/quotes/market_streaming_data.py +66 -0
  201. webull/data/quotes/subscribe/__init__.py +0 -0
  202. webull/data/quotes/subscribe/ask_bid_result.py +49 -0
  203. webull/data/quotes/subscribe/basic_result.py +45 -0
  204. webull/data/quotes/subscribe/broker_result.py +33 -0
  205. webull/data/quotes/subscribe/message_pb2.py +37 -0
  206. webull/data/quotes/subscribe/order_result.py +30 -0
  207. webull/data/quotes/subscribe/payload_type.py +19 -0
  208. webull/data/quotes/subscribe/quote_decoder.py +28 -0
  209. webull/data/quotes/subscribe/quote_result.py +47 -0
  210. webull/data/quotes/subscribe/snapshot_decoder.py +30 -0
  211. webull/data/quotes/subscribe/snapshot_result.py +69 -0
  212. webull/data/quotes/subscribe/tick_decoder.py +29 -0
  213. webull/data/quotes/subscribe/tick_result.py +47 -0
  214. webull/data/request/__init__.py +0 -0
  215. webull/data/request/get_batch_historical_bars_request.py +43 -0
  216. webull/data/request/get_corp_action_request.py +47 -0
  217. webull/data/request/get_eod_bars_request.py +32 -0
  218. webull/data/request/get_historical_bars_request.py +43 -0
  219. webull/data/request/get_instruments_request.py +30 -0
  220. webull/data/request/get_quotes_request.py +35 -0
  221. webull/data/request/get_snapshot_request.py +38 -0
  222. webull/data/request/get_tick_request.py +37 -0
  223. webull/data/request/subscribe_request.py +43 -0
  224. webull/data/request/unsubscribe_request.py +42 -0
  225. webull/trade/__init__.py +2 -0
  226. webull/trade/common/__init__.py +0 -0
  227. webull/trade/common/account_type.py +22 -0
  228. webull/trade/common/category.py +29 -0
  229. webull/trade/common/combo_ticker_type.py +23 -0
  230. webull/trade/common/combo_type.py +31 -0
  231. webull/trade/common/currency.py +24 -0
  232. webull/trade/common/forbid_reason.py +27 -0
  233. webull/trade/common/instrument_type.py +27 -0
  234. webull/trade/common/markets.py +27 -0
  235. webull/trade/common/order_entrust_type.py +21 -0
  236. webull/trade/common/order_side.py +23 -0
  237. webull/trade/common/order_status.py +25 -0
  238. webull/trade/common/order_tif.py +24 -0
  239. webull/trade/common/order_type.py +30 -0
  240. webull/trade/common/trade_policy.py +22 -0
  241. webull/trade/common/trading_date_type.py +24 -0
  242. webull/trade/common/trailing_type.py +23 -0
  243. webull/trade/events/__init__.py +0 -0
  244. webull/trade/events/default_retry_policy.py +64 -0
  245. webull/trade/events/events_pb2.py +43 -0
  246. webull/trade/events/events_pb2_grpc.py +66 -0
  247. webull/trade/events/signature_composer.py +61 -0
  248. webull/trade/events/types.py +21 -0
  249. webull/trade/request/__init__.py +0 -0
  250. webull/trade/request/cancel_order_request.py +28 -0
  251. webull/trade/request/get_account_balance_request.py +28 -0
  252. webull/trade/request/get_account_positions_request.py +30 -0
  253. webull/trade/request/get_account_profile_request.py +26 -0
  254. webull/trade/request/get_app_subscriptions.py +28 -0
  255. webull/trade/request/get_open_orders_request.py +30 -0
  256. webull/trade/request/get_order_detail_request.py +27 -0
  257. webull/trade/request/get_today_orders_request.py +31 -0
  258. webull/trade/request/get_trade_calendar_request.py +30 -0
  259. webull/trade/request/get_trade_instrument_detail_request.py +24 -0
  260. webull/trade/request/get_trade_security_detail_request.py +42 -0
  261. webull/trade/request/get_tradeable_instruments_request.py +27 -0
  262. webull/trade/request/palce_order_request.py +91 -0
  263. webull/trade/request/place_order_request_v2.py +58 -0
  264. webull/trade/request/replace_order_request.py +73 -0
  265. webull/trade/request/replace_order_request_v2.py +38 -0
  266. webull/trade/request/v2/__init__.py +0 -0
  267. webull/trade/request/v2/cancel_option_request.py +28 -0
  268. webull/trade/request/v2/cancel_order_request.py +28 -0
  269. webull/trade/request/v2/get_account_balance_request.py +28 -0
  270. webull/trade/request/v2/get_account_list.py +23 -0
  271. webull/trade/request/v2/get_account_positions_request.py +24 -0
  272. webull/trade/request/v2/get_order_detail_request.py +26 -0
  273. webull/trade/request/v2/get_order_history_request.py +35 -0
  274. webull/trade/request/v2/palce_order_request.py +87 -0
  275. webull/trade/request/v2/place_option_request.py +64 -0
  276. webull/trade/request/v2/preview_option_request.py +28 -0
  277. webull/trade/request/v2/preview_order_request.py +59 -0
  278. webull/trade/request/v2/replace_option_request.py +28 -0
  279. webull/trade/request/v2/replace_order_request.py +57 -0
  280. webull/trade/trade/__init__.py +0 -0
  281. webull/trade/trade/account_info.py +83 -0
  282. webull/trade/trade/order_operation.py +246 -0
  283. webull/trade/trade/trade_calendar.py +37 -0
  284. webull/trade/trade/trade_instrument.py +72 -0
  285. webull/trade/trade/v2/__init__.py +0 -0
  286. webull/trade/trade/v2/account_info_v2.py +55 -0
  287. webull/trade/trade/v2/order_operation_v2.py +206 -0
  288. webull/trade/trade_client.py +43 -0
  289. webull/trade/trade_events_client.py +233 -0
  290. webull_openapi_python_sdk-1.0.0.dist-info/METADATA +28 -0
  291. webull_openapi_python_sdk-1.0.0.dist-info/RECORD +295 -0
  292. webull_openapi_python_sdk-1.0.0.dist-info/WHEEL +5 -0
  293. webull_openapi_python_sdk-1.0.0.dist-info/licenses/LICENSE +202 -0
  294. webull_openapi_python_sdk-1.0.0.dist-info/licenses/NOTICE +56 -0
  295. webull_openapi_python_sdk-1.0.0.dist-info/top_level.txt +2 -0
@@ -0,0 +1,916 @@
1
+ # Copyright 2022 Webull
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ # -*- coding: utf-8 -*-
16
+
17
+ """
18
+ requests.utils
19
+ ~~~~~~~~~~~~~~
20
+
21
+ This module provides utility functions that are used within Requests
22
+ that are also useful for external consumption.
23
+ """
24
+
25
+ import cgi
26
+ import codecs
27
+ import contextlib
28
+ import io
29
+ import os
30
+ import platform
31
+ import re
32
+ import socket
33
+ import struct
34
+ import warnings
35
+
36
+ from .__version__ import __version__
37
+ from . import certs
38
+ # to_native_string is unused here, but imported here for backwards compatibility
39
+ from .compat import parse_http_list as _parse_list_header
40
+ from .compat import (
41
+ quote, urlparse, bytes, str, OrderedDict, unquote, getproxies,
42
+ proxy_bypass, urlunparse, basestring, integer_types, is_py3,
43
+ proxy_bypass_environment, getproxies_environment, Mapping)
44
+ from .cookies import cookiejar_from_dict
45
+ from .structures import CaseInsensitiveDict
46
+ from .exceptions import (
47
+ InvalidURL, InvalidHeader, FileModeWarning, UnrewindableBodyError)
48
+
49
+ NETRC_FILES = ('.netrc', '_netrc')
50
+
51
+ DEFAULT_CA_BUNDLE_PATH = certs.where()
52
+
53
+
54
+ if platform.system() == 'Windows':
55
+ # provide a proxy_bypass version on Windows without DNS lookups
56
+
57
+ def proxy_bypass_registry(host):
58
+ if is_py3:
59
+ import winreg
60
+ else:
61
+ import _winreg as winreg
62
+ try:
63
+ internetSettings = winreg.OpenKey(winreg.HKEY_CURRENT_USER,
64
+ r'Software\Microsoft\Windows\CurrentVersion\Internet Settings')
65
+ proxyEnable = winreg.QueryValueEx(internetSettings,
66
+ 'ProxyEnable')[0]
67
+ proxyOverride = winreg.QueryValueEx(internetSettings,
68
+ 'ProxyOverride')[0]
69
+ except OSError:
70
+ return False
71
+ if not proxyEnable or not proxyOverride:
72
+ return False
73
+
74
+ # make a check value list from the registry entry: replace the
75
+ # '<local>' string by the localhost entry and the corresponding
76
+ # canonical entry.
77
+ proxyOverride = proxyOverride.split(';')
78
+ # now check if we match one of the registry values.
79
+ for test in proxyOverride:
80
+ if test == '<local>':
81
+ if '.' not in host:
82
+ return True
83
+ test = test.replace(".", r"\.") # mask dots
84
+ test = test.replace("*", r".*") # change glob sequence
85
+ test = test.replace("?", r".") # change glob char
86
+ if re.match(test, host, re.I):
87
+ return True
88
+ return False
89
+
90
+ def proxy_bypass(host): # noqa
91
+ """Return True, if the host should be bypassed.
92
+
93
+ Checks proxy settings gathered from the environment, if specified,
94
+ or the registry.
95
+ """
96
+ if getproxies_environment():
97
+ return proxy_bypass_environment(host)
98
+ else:
99
+ return proxy_bypass_registry(host)
100
+
101
+
102
+ def dict_to_sequence(d):
103
+ """Returns an internal sequence dictionary update."""
104
+
105
+ if hasattr(d, 'items'):
106
+ d = d.items()
107
+
108
+ return d
109
+
110
+
111
+ def super_len(o):
112
+ total_length = None
113
+ current_position = 0
114
+
115
+ if hasattr(o, '__len__'):
116
+ total_length = len(o)
117
+
118
+ elif hasattr(o, 'len'):
119
+ total_length = o.len
120
+
121
+ elif hasattr(o, 'fileno'):
122
+ try:
123
+ fileno = o.fileno()
124
+ except io.UnsupportedOperation:
125
+ pass
126
+ else:
127
+ total_length = os.fstat(fileno).st_size
128
+
129
+ # Having used fstat to determine the file length, we need to
130
+ # confirm that this file was opened up in binary mode.
131
+ if 'b' not in o.mode:
132
+ warnings.warn((
133
+ "Requests has determined the content-length for this "
134
+ "request using the binary size of the file: however, the "
135
+ "file has been opened in text mode (i.e. without the 'b' "
136
+ "flag in the mode). This may lead to an incorrect "
137
+ "content-length. In Requests 3.0, support will be removed "
138
+ "for files in text mode."),
139
+ FileModeWarning
140
+ )
141
+
142
+ if hasattr(o, 'tell'):
143
+ try:
144
+ current_position = o.tell()
145
+ except (OSError, IOError):
146
+ # This can happen in some weird situations, such as when the file
147
+ # is actually a special file descriptor like stdin. In this
148
+ # instance, we don't know what the length is, so set it to zero and
149
+ # let requests chunk it instead.
150
+ if total_length is not None:
151
+ current_position = total_length
152
+ else:
153
+ if hasattr(o, 'seek') and total_length is None:
154
+ # StringIO and BytesIO have seek but no useable fileno
155
+ try:
156
+ # seek to end of file
157
+ o.seek(0, 2)
158
+ total_length = o.tell()
159
+
160
+ # seek back to current position to support
161
+ # partially read file-like objects
162
+ o.seek(current_position or 0)
163
+ except (OSError, IOError):
164
+ total_length = 0
165
+
166
+ if total_length is None:
167
+ total_length = 0
168
+
169
+ return max(0, total_length - current_position)
170
+
171
+
172
+ def get_netrc_auth(url, raise_errors=False):
173
+ """Returns the Requests tuple auth for a given url from netrc."""
174
+
175
+ try:
176
+ from netrc import netrc, NetrcParseError
177
+
178
+ netrc_path = None
179
+
180
+ for f in NETRC_FILES:
181
+ try:
182
+ loc = os.path.expanduser('~/{0}'.format(f))
183
+ except KeyError:
184
+ # os.path.expanduser can fail when $HOME is undefined and
185
+ # getpwuid fails. See http://bugs.python.org/issue20164 &
186
+ # https://github.com/requests/requests/issues/1846
187
+ return
188
+
189
+ if os.path.exists(loc):
190
+ netrc_path = loc
191
+ break
192
+
193
+ # Abort early if there isn't one.
194
+ if netrc_path is None:
195
+ return
196
+
197
+ ri = urlparse(url)
198
+
199
+ # Strip port numbers from netloc. This weird `if...encode`` dance is
200
+ # used for Python 3.2, which doesn't support unicode literals.
201
+ splitstr = b':'
202
+ if isinstance(url, str):
203
+ splitstr = splitstr.decode('ascii')
204
+ host = ri.netloc.split(splitstr)[0]
205
+
206
+ try:
207
+ _netrc = netrc(netrc_path).authenticators(host)
208
+ if _netrc:
209
+ # Return with login / password
210
+ login_i = (0 if _netrc[0] else 1)
211
+ return (_netrc[login_i], _netrc[2])
212
+ except (NetrcParseError, IOError):
213
+ # If there was a parsing error or a permissions issue reading the file,
214
+ # we'll just skip netrc auth unless explicitly asked to raise errors.
215
+ if raise_errors:
216
+ raise
217
+
218
+ # AppEngine hackiness.
219
+ except (ImportError, AttributeError):
220
+ pass
221
+
222
+
223
+ def guess_filename(obj):
224
+ """Tries to guess the filename of the given object."""
225
+ name = getattr(obj, 'name', None)
226
+ if (name and isinstance(name, basestring) and name[0] != '<' and
227
+ name[-1] != '>'):
228
+ return os.path.basename(name)
229
+
230
+
231
+ def from_key_val_list(value):
232
+ """Take an object and test to see if it can be represented as a
233
+ dictionary. Unless it can not be represented as such, return an
234
+ OrderedDict, e.g.,
235
+
236
+ ::
237
+
238
+ >>> from_key_val_list([('key', 'val')])
239
+ OrderedDict([('key', 'val')])
240
+ >>> from_key_val_list('string')
241
+ ValueError: need more than 1 value to unpack
242
+ >>> from_key_val_list({'key': 'val'})
243
+ OrderedDict([('key', 'val')])
244
+
245
+ :rtype: OrderedDict
246
+ """
247
+ if value is None:
248
+ return None
249
+
250
+ if isinstance(value, (str, bytes, bool, int)):
251
+ raise ValueError('cannot encode objects that are not 2-tuples')
252
+
253
+ return OrderedDict(value)
254
+
255
+
256
+ def to_key_val_list(value):
257
+ """Take an object and test to see if it can be represented as a
258
+ dictionary. If it can be, return a list of tuples, e.g.,
259
+
260
+ ::
261
+
262
+ >>> to_key_val_list([('key', 'val')])
263
+ [('key', 'val')]
264
+ >>> to_key_val_list({'key': 'val'})
265
+ [('key', 'val')]
266
+ >>> to_key_val_list('string')
267
+ ValueError: cannot encode objects that are not 2-tuples.
268
+
269
+ :rtype: list
270
+ """
271
+ if value is None:
272
+ return None
273
+
274
+ if isinstance(value, (str, bytes, bool, int)):
275
+ raise ValueError('cannot encode objects that are not 2-tuples')
276
+
277
+ if isinstance(value, Mapping):
278
+ value = value.items()
279
+
280
+ return list(value)
281
+
282
+
283
+ # From mitsuhiko/werkzeug (used with permission).
284
+ def parse_list_header(value):
285
+ """Parse lists as described by RFC 2068 Section 2.
286
+
287
+ In particular, parse comma-separated lists where the elements of
288
+ the list may include quoted-strings. A quoted-string could
289
+ contain a comma. A non-quoted string could have quotes in the
290
+ middle. Quotes are removed automatically after parsing.
291
+
292
+ It basically works like :func:`parse_set_header` just that items
293
+ may appear multiple times and case sensitivity is preserved.
294
+
295
+ The return value is a standard :class:`list`:
296
+
297
+ >>> parse_list_header('token, "quoted value"')
298
+ ['token', 'quoted value']
299
+
300
+ To create a header from the :class:`list` again, use the
301
+ :func:`dump_header` function.
302
+
303
+ :param value: a string with a list header.
304
+ :return: :class:`list`
305
+ :rtype: list
306
+ """
307
+ result = []
308
+ for item in _parse_list_header(value):
309
+ if item[:1] == item[-1:] == '"':
310
+ item = unquote_header_value(item[1:-1])
311
+ result.append(item)
312
+ return result
313
+
314
+
315
+ # From mitsuhiko/werkzeug (used with permission).
316
+ def parse_dict_header(value):
317
+ """Parse lists of key, value pairs as described by RFC 2068 Section 2 and
318
+ convert them into a python dict:
319
+
320
+ >>> d = parse_dict_header('foo="is a fish", bar="as well"')
321
+ >>> type(d) is dict
322
+ True
323
+ >>> sorted(d.items())
324
+ [('bar', 'as well'), ('foo', 'is a fish')]
325
+
326
+ If there is no value for a key it will be `None`:
327
+
328
+ >>> parse_dict_header('key_without_value')
329
+ {'key_without_value': None}
330
+
331
+ To create a header from the :class:`dict` again, use the
332
+ :func:`dump_header` function.
333
+
334
+ :param value: a string with a dict header.
335
+ :return: :class:`dict`
336
+ :rtype: dict
337
+ """
338
+ result = {}
339
+ for item in _parse_list_header(value):
340
+ if '=' not in item:
341
+ result[item] = None
342
+ continue
343
+ name, value = item.split('=', 1)
344
+ if value[:1] == value[-1:] == '"':
345
+ value = unquote_header_value(value[1:-1])
346
+ result[name] = value
347
+ return result
348
+
349
+
350
+ # From mitsuhiko/werkzeug (used with permission).
351
+ def unquote_header_value(value, is_filename=False):
352
+ r"""Unquotes a header value. (Reversal of :func:`quote_header_value`).
353
+ This does not use the real unquoting but what browsers are actually
354
+ using for quoting.
355
+
356
+ :param value: the header value to unquote.
357
+ :rtype: str
358
+ """
359
+ if value and value[0] == value[-1] == '"':
360
+ # this is not the real unquoting, but fixing this so that the
361
+ # RFC is met will result in bugs with internet explorer and
362
+ # probably some other browsers as well. IE for example is
363
+ # uploading files with "C:\foo\bar.txt" as filename
364
+ value = value[1:-1]
365
+
366
+ # if this is a filename and the starting characters look like
367
+ # a UNC path, then just return the value without quotes. Using the
368
+ # replace sequence below on a UNC path has the effect of turning
369
+ # the leading double slash into a single slash and then
370
+ # _fix_ie_filename() doesn't work correctly. See #458.
371
+ if not is_filename or value[:2] != '\\\\':
372
+ return value.replace('\\\\', '\\').replace('\\"', '"')
373
+ return value
374
+
375
+
376
+ def dict_from_cookiejar(cj):
377
+ """Returns a key/value dictionary from a CookieJar.
378
+
379
+ :param cj: CookieJar object to extract cookies from.
380
+ :rtype: dict
381
+ """
382
+
383
+ cookie_dict = {}
384
+
385
+ for cookie in cj:
386
+ cookie_dict[cookie.name] = cookie.value
387
+
388
+ return cookie_dict
389
+
390
+
391
+ def add_dict_to_cookiejar(cj, cookie_dict):
392
+ """Returns a CookieJar from a key/value dictionary.
393
+
394
+ :param cj: CookieJar to insert cookies into.
395
+ :param cookie_dict: Dict of key/values to insert into CookieJar.
396
+ :rtype: CookieJar
397
+ """
398
+
399
+ return cookiejar_from_dict(cookie_dict, cj)
400
+
401
+
402
+ def get_encodings_from_content(content):
403
+ """Returns encodings from given content string.
404
+
405
+ :param content: bytestring to extract encodings from.
406
+ """
407
+ warnings.warn((
408
+ 'In requests 3.0, get_encodings_from_content will be removed. For '
409
+ 'more information, please see the discussion on issue #2266. (This'
410
+ ' warning should only appear once.)'),
411
+ DeprecationWarning)
412
+
413
+ charset_re = re.compile(r'<meta.*?charset=["\']*(.+?)["\'>]', flags=re.I)
414
+ pragma_re = re.compile(r'<meta.*?content=["\']*;?charset=(.+?)["\'>]', flags=re.I)
415
+ xml_re = re.compile(r'^<\?xml.*?encoding=["\']*(.+?)["\'>]')
416
+
417
+ return (charset_re.findall(content) +
418
+ pragma_re.findall(content) +
419
+ xml_re.findall(content))
420
+
421
+
422
+ def get_encoding_from_headers(headers):
423
+ """Returns encodings from given HTTP Header Dict.
424
+
425
+ :param headers: dictionary to extract encoding from.
426
+ :rtype: str
427
+ """
428
+
429
+ content_type = headers.get('content-type')
430
+
431
+ if not content_type:
432
+ return None
433
+
434
+ content_type, params = cgi.parse_header(content_type)
435
+
436
+ if 'charset' in params:
437
+ return params['charset'].strip("'\"")
438
+
439
+ if 'text' in content_type:
440
+ return 'ISO-8859-1'
441
+
442
+
443
+ def stream_decode_response_unicode(iterator, r):
444
+ """Stream decodes a iterator."""
445
+
446
+ if r.encoding is None:
447
+ for item in iterator:
448
+ yield item
449
+ return
450
+
451
+ decoder = codecs.getincrementaldecoder(r.encoding)(errors='replace')
452
+ for chunk in iterator:
453
+ rv = decoder.decode(chunk)
454
+ if rv:
455
+ yield rv
456
+ rv = decoder.decode(b'', final=True)
457
+ if rv:
458
+ yield rv
459
+
460
+
461
+ def iter_slices(string, slice_length):
462
+ """Iterate over slices of a string."""
463
+ pos = 0
464
+ if slice_length is None or slice_length <= 0:
465
+ slice_length = len(string)
466
+ while pos < len(string):
467
+ yield string[pos:pos + slice_length]
468
+ pos += slice_length
469
+
470
+
471
+ def get_unicode_from_response(r):
472
+ """Returns the requested content back in unicode.
473
+
474
+ :param r: Response object to get unicode content from.
475
+
476
+ Tried:
477
+
478
+ 1. charset from content-type
479
+ 2. fall back and replace all unicode characters
480
+
481
+ :rtype: str
482
+ """
483
+ warnings.warn((
484
+ 'In requests 3.0, get_unicode_from_response will be removed. For '
485
+ 'more information, please see the discussion on issue #2266. (This'
486
+ ' warning should only appear once.)'),
487
+ DeprecationWarning)
488
+
489
+ tried_encodings = []
490
+
491
+ # Try charset from content-type
492
+ encoding = get_encoding_from_headers(r.headers)
493
+
494
+ if encoding:
495
+ try:
496
+ return str(r.content, encoding)
497
+ except UnicodeError:
498
+ tried_encodings.append(encoding)
499
+
500
+ # Fall back:
501
+ try:
502
+ return str(r.content, encoding, errors='replace')
503
+ except TypeError:
504
+ return r.content
505
+
506
+
507
+ # The unreserved URI characters (RFC 3986)
508
+ UNRESERVED_SET = frozenset(
509
+ "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz" + "0123456789-._~")
510
+
511
+
512
+ def unquote_unreserved(uri):
513
+ """Un-escape any percent-escape sequences in a URI that are unreserved
514
+ characters. This leaves all reserved, illegal and non-ASCII bytes encoded.
515
+
516
+ :rtype: str
517
+ """
518
+ parts = uri.split('%')
519
+ for i in range(1, len(parts)):
520
+ h = parts[i][0:2]
521
+ if len(h) == 2 and h.isalnum():
522
+ try:
523
+ c = chr(int(h, 16))
524
+ except ValueError:
525
+ raise InvalidURL("Invalid percent-escape sequence: '%s'" % h)
526
+
527
+ if c in UNRESERVED_SET:
528
+ parts[i] = c + parts[i][2:]
529
+ else:
530
+ parts[i] = '%' + parts[i]
531
+ else:
532
+ parts[i] = '%' + parts[i]
533
+ return ''.join(parts)
534
+
535
+
536
+ def requote_uri(uri):
537
+ """Re-quote the given URI.
538
+
539
+ This function passes the given URI through an unquote/quote cycle to
540
+ ensure that it is fully and consistently quoted.
541
+
542
+ :rtype: str
543
+ """
544
+ safe_with_percent = "!#$%&'()*+,/:;=?@[]~"
545
+ safe_without_percent = "!#$&'()*+,/:;=?@[]~"
546
+ try:
547
+ # Unquote only the unreserved characters
548
+ # Then quote only illegal characters (do not quote reserved,
549
+ # unreserved, or '%')
550
+ return quote(unquote_unreserved(uri), safe=safe_with_percent)
551
+ except InvalidURL:
552
+ # We couldn't unquote the given URI, so let's try quoting it, but
553
+ # there may be unquoted '%'s in the URI. We need to make sure they're
554
+ # properly quoted so they do not cause issues elsewhere.
555
+ return quote(uri, safe=safe_without_percent)
556
+
557
+
558
+ def address_in_network(ip, net):
559
+ """This function allows you to check if an IP belongs to a network subnet
560
+
561
+ Example: returns True if ip = 192.168.1.1 and net = 192.168.1.0/24
562
+ returns False if ip = 192.168.1.1 and net = 192.168.100.0/24
563
+
564
+ :rtype: bool
565
+ """
566
+ ipaddr = struct.unpack('=L', socket.inet_aton(ip))[0]
567
+ netaddr, bits = net.split('/')
568
+ netmask = struct.unpack('=L', socket.inet_aton(dotted_netmask(int(bits))))[0]
569
+ network = struct.unpack('=L', socket.inet_aton(netaddr))[0] & netmask
570
+ return (ipaddr & netmask) == (network & netmask)
571
+
572
+
573
+ def dotted_netmask(mask):
574
+ """Converts mask from /xx format to xxx.xxx.xxx.xxx
575
+
576
+ Example: if mask is 24 function returns 255.255.255.0
577
+
578
+ :rtype: str
579
+ """
580
+ bits = 0xffffffff ^ (1 << 32 - mask) - 1
581
+ return socket.inet_ntoa(struct.pack('>I', bits))
582
+
583
+
584
+ def is_ipv4_address(string_ip):
585
+ """
586
+ :rtype: bool
587
+ """
588
+ try:
589
+ socket.inet_aton(string_ip)
590
+ except socket.error:
591
+ return False
592
+ return True
593
+
594
+
595
+ def is_valid_cidr(string_network):
596
+ """
597
+ Very simple check of the cidr format in no_proxy variable.
598
+
599
+ :rtype: bool
600
+ """
601
+ if string_network.count('/') == 1:
602
+ try:
603
+ mask = int(string_network.split('/')[1])
604
+ except ValueError:
605
+ return False
606
+
607
+ if mask < 1 or mask > 32:
608
+ return False
609
+
610
+ try:
611
+ socket.inet_aton(string_network.split('/')[0])
612
+ except socket.error:
613
+ return False
614
+ else:
615
+ return False
616
+ return True
617
+
618
+
619
+ @contextlib.contextmanager
620
+ def set_environ(env_name, value):
621
+ """Set the environment variable 'env_name' to 'value'
622
+
623
+ Save previous value, yield, and then restore the previous value stored in
624
+ the environment variable 'env_name'.
625
+
626
+ If 'value' is None, do nothing"""
627
+ value_changed = value is not None
628
+ if value_changed:
629
+ old_value = os.environ.get(env_name)
630
+ os.environ[env_name] = value
631
+ try:
632
+ yield
633
+ finally:
634
+ if value_changed:
635
+ if old_value is None:
636
+ del os.environ[env_name]
637
+ else:
638
+ os.environ[env_name] = old_value
639
+
640
+
641
+ def should_bypass_proxies(url, no_proxy):
642
+ """
643
+ Returns whether we should bypass proxies or not.
644
+
645
+ :rtype: bool
646
+ """
647
+ get_proxy = lambda k: os.environ.get(k) or os.environ.get(k.upper())
648
+
649
+ # First check whether no_proxy is defined. If it is, check that the URL
650
+ # we're getting isn't in the no_proxy list.
651
+ no_proxy_arg = no_proxy
652
+ if no_proxy is None:
653
+ no_proxy = get_proxy('no_proxy')
654
+ netloc = urlparse(url).netloc
655
+
656
+ if no_proxy:
657
+ # We need to check whether we match here. We need to see if we match
658
+ # the end of the netloc, both with and without the port.
659
+ no_proxy = (
660
+ host for host in no_proxy.replace(' ', '').split(',') if host
661
+ )
662
+
663
+ ip = netloc.split(':')[0]
664
+ if is_ipv4_address(ip):
665
+ for proxy_ip in no_proxy:
666
+ if is_valid_cidr(proxy_ip):
667
+ if address_in_network(ip, proxy_ip):
668
+ return True
669
+ elif ip == proxy_ip:
670
+ # If no_proxy ip was defined in plain IP notation instead of cidr notation &
671
+ # matches the IP of the index
672
+ return True
673
+ else:
674
+ for host in no_proxy:
675
+ if netloc.endswith(host) or netloc.split(':')[0].endswith(host):
676
+ # The URL does match something in no_proxy, so we don't want
677
+ # to apply the proxies on this URL.
678
+ return True
679
+
680
+ # If the system proxy settings indicate that this URL should be bypassed,
681
+ # don't proxy.
682
+ # The proxy_bypass function is incredibly buggy on OS X in early versions
683
+ # of Python 2.6, so allow this call to fail. Only catch the specific
684
+ # exceptions we've seen, though: this call failing in other ways can reveal
685
+ # legitimate problems.
686
+ with set_environ('no_proxy', no_proxy_arg):
687
+ try:
688
+ bypass = proxy_bypass(netloc)
689
+ except (TypeError, socket.gaierror):
690
+ bypass = False
691
+
692
+ if bypass:
693
+ return True
694
+
695
+ return False
696
+
697
+
698
+ def get_environ_proxies(url, no_proxy=None):
699
+ """
700
+ Return a dict of environment proxies.
701
+
702
+ :rtype: dict
703
+ """
704
+ if should_bypass_proxies(url, no_proxy=no_proxy):
705
+ return {}
706
+ else:
707
+ return getproxies()
708
+
709
+
710
+ def select_proxy(url, proxies):
711
+ """Select a proxy for the url, if applicable.
712
+
713
+ :param url: The url being for the request
714
+ :param proxies: A dictionary of schemes or schemes and hosts to proxy URLs
715
+ """
716
+ proxies = proxies or {}
717
+ urlparts = urlparse(url)
718
+ if urlparts.hostname is None:
719
+ return proxies.get(urlparts.scheme, proxies.get('all'))
720
+
721
+ proxy_keys = [
722
+ urlparts.scheme + '://' + urlparts.hostname,
723
+ urlparts.scheme,
724
+ 'all://' + urlparts.hostname,
725
+ 'all',
726
+ ]
727
+ proxy = None
728
+ for proxy_key in proxy_keys:
729
+ if proxy_key in proxies:
730
+ proxy = proxies[proxy_key]
731
+ break
732
+
733
+ return proxy
734
+
735
+
736
+ def default_user_agent(name="python-requests"):
737
+ """
738
+ Return a string representing the default user agent.
739
+
740
+ :rtype: str
741
+ """
742
+ return '%s/%s' % (name, __version__)
743
+
744
+
745
+ def default_headers():
746
+ """
747
+ :rtype: requests.structures.CaseInsensitiveDict
748
+ """
749
+ return CaseInsensitiveDict({
750
+ 'User-Agent': default_user_agent(),
751
+ 'Accept-Encoding': ', '.join(('gzip', 'deflate')),
752
+ 'Accept': '*/*',
753
+ 'Connection': 'keep-alive',
754
+ })
755
+
756
+
757
+ def parse_header_links(value):
758
+ """Return a dict of parsed link headers proxies.
759
+
760
+ i.e. Link: <http:/.../front.jpeg>; rel=front; type="image/jpeg",<http://.../back.jpeg>; rel=back;type="image/jpeg"
761
+
762
+ :rtype: list
763
+ """
764
+
765
+ links = []
766
+
767
+ replace_chars = ' \'"'
768
+
769
+ for val in re.split(', *<', value):
770
+ try:
771
+ url, params = val.split(';', 1)
772
+ except ValueError:
773
+ url, params = val, ''
774
+
775
+ link = {'url': url.strip('<> \'"')}
776
+
777
+ for param in params.split(';'):
778
+ try:
779
+ key, value = param.split('=')
780
+ except ValueError:
781
+ break
782
+
783
+ link[key.strip(replace_chars)] = value.strip(replace_chars)
784
+
785
+ links.append(link)
786
+
787
+ return links
788
+
789
+
790
+ # Null bytes; no need to recreate these on each call to guess_json_utf
791
+ _null = '\x00'.encode('ascii') # encoding to ASCII for Python 3
792
+ _null2 = _null * 2
793
+ _null3 = _null * 3
794
+
795
+
796
+ def guess_json_utf(data):
797
+ """
798
+ :rtype: str
799
+ """
800
+ # JSON always starts with two ASCII characters, so detection is as
801
+ # easy as counting the nulls and from their location and count
802
+ # determine the encoding. Also detect a BOM, if present.
803
+ sample = data[:4]
804
+ if sample in (codecs.BOM_UTF32_LE, codecs.BOM_UTF32_BE):
805
+ return 'utf-32' # BOM included
806
+ if sample[:3] == codecs.BOM_UTF8:
807
+ return 'utf-8-sig' # BOM included, MS style (discouraged)
808
+ if sample[:2] in (codecs.BOM_UTF16_LE, codecs.BOM_UTF16_BE):
809
+ return 'utf-16' # BOM included
810
+ nullcount = sample.count(_null)
811
+ if nullcount == 0:
812
+ return 'utf-8'
813
+ if nullcount == 2:
814
+ if sample[::2] == _null2: # 1st and 3rd are null
815
+ return 'utf-16-be'
816
+ if sample[1::2] == _null2: # 2nd and 4th are null
817
+ return 'utf-16-le'
818
+ # Did not detect 2 valid UTF-16 ascii-range characters
819
+ if nullcount == 3:
820
+ if sample[:3] == _null3:
821
+ return 'utf-32-be'
822
+ if sample[1:] == _null3:
823
+ return 'utf-32-le'
824
+ # Did not detect a valid UTF-32 ascii-range character
825
+ return None
826
+
827
+
828
+ def prepend_scheme_if_needed(url, new_scheme):
829
+ """Given a URL that may or may not have a scheme, prepend the given scheme.
830
+ Does not replace a present scheme with the one provided as an argument.
831
+
832
+ :rtype: str
833
+ """
834
+ scheme, netloc, path, params, query, fragment = urlparse(url, new_scheme)
835
+
836
+ # urlparse is a finicky beast, and sometimes decides that there isn't a
837
+ # netloc present. Assume that it's being over-cautious, and switch netloc
838
+ # and path if urlparse decided there was no netloc.
839
+ if not netloc:
840
+ netloc, path = path, netloc
841
+
842
+ return urlunparse((scheme, netloc, path, params, query, fragment))
843
+
844
+
845
+ def get_auth_from_url(url):
846
+ """Given a url with authentication components, extract them into a tuple of
847
+ username,password.
848
+
849
+ :rtype: (str,str)
850
+ """
851
+ parsed = urlparse(url)
852
+
853
+ try:
854
+ auth = (unquote(parsed.username), unquote(parsed.password))
855
+ except (AttributeError, TypeError):
856
+ auth = ('', '')
857
+
858
+ return auth
859
+
860
+
861
+ # Moved outside of function to avoid recompile every call
862
+ _CLEAN_HEADER_REGEX_BYTE = re.compile(b'^\\S[^\\r\\n]*$|^$')
863
+ _CLEAN_HEADER_REGEX_STR = re.compile(r'^\S[^\r\n]*$|^$')
864
+
865
+
866
+ def check_header_validity(header):
867
+ """Verifies that header value is a string which doesn't contain
868
+ leading whitespace or return characters. This prevents unintended
869
+ header injection.
870
+
871
+ :param header: tuple, in the format (name, value).
872
+ """
873
+ name, value = header
874
+
875
+ if isinstance(value, bytes):
876
+ pat = _CLEAN_HEADER_REGEX_BYTE
877
+ else:
878
+ pat = _CLEAN_HEADER_REGEX_STR
879
+ try:
880
+ if not pat.match(value):
881
+ raise InvalidHeader("Invalid return character or leading space in header: %s" % name)
882
+ except TypeError:
883
+ raise InvalidHeader("Header value %s must be of type str or bytes, "
884
+ "not %s" % (value, type(value)))
885
+
886
+
887
+ def urldefragauth(url):
888
+ """
889
+ Given a url remove the fragment and the authentication part.
890
+
891
+ :rtype: str
892
+ """
893
+ scheme, netloc, path, params, query, fragment = urlparse(url)
894
+
895
+ # see func:`prepend_scheme_if_needed`
896
+ if not netloc:
897
+ netloc, path = path, netloc
898
+
899
+ netloc = netloc.rsplit('@', 1)[-1]
900
+
901
+ return urlunparse((scheme, netloc, path, params, query, ''))
902
+
903
+
904
+ def rewind_body(prepared_request):
905
+ """Move file pointer back to its recorded starting position
906
+ so it can be read again on redirect.
907
+ """
908
+ body_seek = getattr(prepared_request.body, 'seek', None)
909
+ if body_seek is not None and isinstance(prepared_request._body_position, integer_types):
910
+ try:
911
+ body_seek(prepared_request._body_position)
912
+ except (IOError, OSError):
913
+ raise UnrewindableBodyError("An error occurred when rewinding request "
914
+ "body for redirect.")
915
+ else:
916
+ raise UnrewindableBodyError("Unable to rewind request body for redirect.")