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,960 @@
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.models
19
+ ~~~~~~~~~~~~~~~
20
+
21
+ This module contains the primary objects that power Requests.
22
+ """
23
+
24
+ import datetime
25
+
26
+ # Import encoding now, to avoid implicit import later.
27
+ # Implicit import within threads may cause LookupError when standard library is in a ZIP,
28
+ # such as in Embedded Python. See https://github.com/requests/requests/issues/3578.
29
+
30
+ from .packages.urllib3.fields import RequestField
31
+ from .packages.urllib3.filepost import encode_multipart_formdata
32
+ from .packages.urllib3.util import parse_url
33
+ from .packages.urllib3.exceptions import (
34
+ DecodeError, ReadTimeoutError, ProtocolError, LocationParseError)
35
+
36
+ from io import UnsupportedOperation
37
+ from .hooks import default_hooks
38
+ from .structures import CaseInsensitiveDict
39
+
40
+ from .auth import HTTPBasicAuth
41
+ from .cookies import cookiejar_from_dict, get_cookie_header, _copy_cookie_jar
42
+ from .exceptions import (
43
+ HTTPError, MissingSchema, InvalidURL, ChunkedEncodingError,
44
+ ContentDecodingError, ConnectionError, StreamConsumedError)
45
+ from ._internal_utils import to_native_string, unicode_is_ascii
46
+ from .utils import (
47
+ guess_filename, get_auth_from_url, requote_uri,
48
+ stream_decode_response_unicode, to_key_val_list, parse_header_links,
49
+ iter_slices, guess_json_utf, super_len, check_header_validity)
50
+ from .compat import (
51
+ Callable, Mapping,
52
+ cookielib, urlunparse, urlsplit, urlencode, str, bytes,
53
+ is_py2, chardet, builtin_str, basestring)
54
+ from .compat import json as complexjson
55
+ from .status_codes import codes
56
+
57
+ #: The set of HTTP status codes that indicate an automatically
58
+ #: processable redirect.
59
+ REDIRECT_STATI = (
60
+ codes.moved, # 301
61
+ codes.found, # 302
62
+ codes.other, # 303
63
+ codes.temporary_redirect, # 307
64
+ codes.permanent_redirect, # 308
65
+ )
66
+
67
+ DEFAULT_REDIRECT_LIMIT = 30
68
+ CONTENT_CHUNK_SIZE = 10 * 1024
69
+ ITER_CHUNK_SIZE = 512
70
+
71
+
72
+ class RequestEncodingMixin(object):
73
+ @property
74
+ def path_url(self):
75
+ """Build the path URL to use."""
76
+
77
+ url = []
78
+
79
+ p = urlsplit(self.url)
80
+
81
+ path = p.path
82
+ if not path:
83
+ path = '/'
84
+
85
+ url.append(path)
86
+
87
+ query = p.query
88
+ if query:
89
+ url.append('?')
90
+ url.append(query)
91
+
92
+ return ''.join(url)
93
+
94
+ @staticmethod
95
+ def _encode_params(data):
96
+ """Encode parameters in a piece of data.
97
+
98
+ Will successfully encode parameters when passed as a dict or a list of
99
+ 2-tuples. Order is retained if data is a list of 2-tuples but arbitrary
100
+ if parameters are supplied as a dict.
101
+ """
102
+
103
+ if isinstance(data, (str, bytes)):
104
+ return data
105
+ elif hasattr(data, 'read'):
106
+ return data
107
+ elif hasattr(data, '__iter__'):
108
+ result = []
109
+ for k, vs in to_key_val_list(data):
110
+ if isinstance(vs, basestring) or not hasattr(vs, '__iter__'):
111
+ vs = [vs]
112
+ for v in vs:
113
+ if v is not None:
114
+ result.append(
115
+ (k.encode('utf-8') if isinstance(k, str) else k,
116
+ v.encode('utf-8') if isinstance(v, str) else v))
117
+ return urlencode(result, doseq=True)
118
+ else:
119
+ return data
120
+
121
+ @staticmethod
122
+ def _encode_files(files, data):
123
+ """Build the body for a multipart/form-data request.
124
+
125
+ Will successfully encode files when passed as a dict or a list of
126
+ tuples. Order is retained if data is a list of tuples but arbitrary
127
+ if parameters are supplied as a dict.
128
+ The tuples may be 2-tuples (filename, fileobj), 3-tuples (filename, fileobj, contentype)
129
+ or 4-tuples (filename, fileobj, contentype, custom_headers).
130
+ """
131
+ if (not files):
132
+ raise ValueError("Files must be provided.")
133
+ elif isinstance(data, basestring):
134
+ raise ValueError("Data must not be a string.")
135
+
136
+ new_fields = []
137
+ fields = to_key_val_list(data or {})
138
+ files = to_key_val_list(files or {})
139
+
140
+ for field, val in fields:
141
+ if isinstance(val, basestring) or not hasattr(val, '__iter__'):
142
+ val = [val]
143
+ for v in val:
144
+ if v is not None:
145
+ # Don't call str() on bytestrings: in Py3 it all goes wrong.
146
+ if not isinstance(v, bytes):
147
+ v = str(v)
148
+
149
+ new_fields.append(
150
+ (field.decode('utf-8') if isinstance(field, bytes) else field,
151
+ v.encode('utf-8') if isinstance(v, str) else v))
152
+
153
+ for (k, v) in files:
154
+ # support for explicit filename
155
+ ft = None
156
+ fh = None
157
+ if isinstance(v, (tuple, list)):
158
+ if len(v) == 2:
159
+ fn, fp = v
160
+ elif len(v) == 3:
161
+ fn, fp, ft = v
162
+ else:
163
+ fn, fp, ft, fh = v
164
+ else:
165
+ fn = guess_filename(v) or k
166
+ fp = v
167
+
168
+ if isinstance(fp, (str, bytes, bytearray)):
169
+ fdata = fp
170
+ else:
171
+ fdata = fp.read()
172
+
173
+ rf = RequestField(name=k, data=fdata, filename=fn, headers=fh)
174
+ rf.make_multipart(content_type=ft)
175
+ new_fields.append(rf)
176
+
177
+ body, content_type = encode_multipart_formdata(new_fields)
178
+
179
+ return body, content_type
180
+
181
+
182
+ class RequestHooksMixin(object):
183
+ def register_hook(self, event, hook):
184
+ """Properly register a hook."""
185
+
186
+ if event not in self.hooks:
187
+ raise ValueError('Unsupported event specified, with event name "%s"' % (event))
188
+
189
+ if isinstance(hook, Callable):
190
+ self.hooks[event].append(hook)
191
+ elif hasattr(hook, '__iter__'):
192
+ self.hooks[event].extend(h for h in hook if isinstance(h, Callable))
193
+
194
+ def deregister_hook(self, event, hook):
195
+ """Deregister a previously registered hook.
196
+ Returns True if the hook existed, False if not.
197
+ """
198
+
199
+ try:
200
+ self.hooks[event].remove(hook)
201
+ return True
202
+ except ValueError:
203
+ return False
204
+
205
+
206
+ class Request(RequestHooksMixin):
207
+ """A user-created :class:`Request <Request>` object.
208
+
209
+ Used to prepare a :class:`PreparedRequest <PreparedRequest>`, which is sent to the server.
210
+
211
+ :param method: HTTP method to use.
212
+ :param url: URL to send.
213
+ :param headers: dictionary of headers to send.
214
+ :param files: dictionary of {filename: fileobject} files to multipart upload.
215
+ :param data: the body to attach to the request. If a dictionary is provided, form-encoding will take place.
216
+ :param json: json for the body to attach to the request (if files or data is not specified).
217
+ :param params: dictionary of URL parameters to append to the URL.
218
+ :param auth: Auth handler or (user, pass) tuple.
219
+ :param cookies: dictionary or CookieJar of cookies to attach to this request.
220
+ :param hooks: dictionary of callback hooks, for internal usage.
221
+
222
+ Usage::
223
+
224
+ >>> import requests
225
+ >>> req = requests.Request('GET', 'http://httpbin.org/get')
226
+ >>> req.prepare()
227
+ <PreparedRequest [GET]>
228
+ """
229
+
230
+ def __init__(self,
231
+ method=None, url=None, headers=None, files=None, data=None,
232
+ params=None, auth=None, cookies=None, hooks=None, json=None):
233
+
234
+ # Default empty dicts for dict params.
235
+ data = [] if data is None else data
236
+ files = [] if files is None else files
237
+ headers = {} if headers is None else headers
238
+ params = {} if params is None else params
239
+ hooks = {} if hooks is None else hooks
240
+
241
+ self.hooks = default_hooks()
242
+ for (k, v) in list(hooks.items()):
243
+ self.register_hook(event=k, hook=v)
244
+
245
+ self.method = method
246
+ self.url = url
247
+ self.headers = headers
248
+ self.files = files
249
+ self.data = data
250
+ self.json = json
251
+ self.params = params
252
+ self.auth = auth
253
+ self.cookies = cookies
254
+
255
+ def __repr__(self):
256
+ return '<Request [%s]>' % (self.method)
257
+
258
+ def prepare(self):
259
+ """Constructs a :class:`PreparedRequest <PreparedRequest>` for transmission and returns it."""
260
+ p = PreparedRequest()
261
+ p.prepare(
262
+ method=self.method,
263
+ url=self.url,
264
+ headers=self.headers,
265
+ files=self.files,
266
+ data=self.data,
267
+ json=self.json,
268
+ params=self.params,
269
+ auth=self.auth,
270
+ cookies=self.cookies,
271
+ hooks=self.hooks,
272
+ )
273
+ return p
274
+
275
+
276
+ class PreparedRequest(RequestEncodingMixin, RequestHooksMixin):
277
+ """The fully mutable :class:`PreparedRequest <PreparedRequest>` object,
278
+ containing the exact bytes that will be sent to the server.
279
+
280
+ Generated from either a :class:`Request <Request>` object or manually.
281
+
282
+ Usage::
283
+
284
+ >>> import requests
285
+ >>> req = requests.Request('GET', 'http://httpbin.org/get')
286
+ >>> r = req.prepare()
287
+ <PreparedRequest [GET]>
288
+
289
+ >>> s = requests.Session()
290
+ >>> s.send(r)
291
+ <Response [200]>
292
+ """
293
+
294
+ def __init__(self):
295
+ #: HTTP verb to send to the server.
296
+ self.method = None
297
+ #: HTTP URL to send the request to.
298
+ self.url = None
299
+ #: dictionary of HTTP headers.
300
+ self.headers = None
301
+ # The `CookieJar` used to create the Cookie header will be stored here
302
+ # after prepare_cookies is called
303
+ self._cookies = None
304
+ #: request body to send to the server.
305
+ self.body = None
306
+ #: dictionary of callback hooks, for internal usage.
307
+ self.hooks = default_hooks()
308
+ #: integer denoting starting position of a readable file-like body.
309
+ self._body_position = None
310
+
311
+ def prepare(self,
312
+ method=None, url=None, headers=None, files=None, data=None,
313
+ params=None, auth=None, cookies=None, hooks=None, json=None):
314
+ """Prepares the entire request with the given parameters."""
315
+
316
+ self.prepare_method(method)
317
+ self.prepare_url(url, params)
318
+ self.prepare_headers(headers)
319
+ self.prepare_cookies(cookies)
320
+ self.prepare_body(data, files, json)
321
+ self.prepare_auth(auth, url)
322
+
323
+ # Note that prepare_auth must be last to enable authentication schemes
324
+ # such as OAuth to work on a fully prepared request.
325
+
326
+ # This MUST go after prepare_auth. Authenticators could add a hook
327
+ self.prepare_hooks(hooks)
328
+
329
+ def __repr__(self):
330
+ return '<PreparedRequest [%s]>' % (self.method)
331
+
332
+ def copy(self):
333
+ p = PreparedRequest()
334
+ p.method = self.method
335
+ p.url = self.url
336
+ p.headers = self.headers.copy() if self.headers is not None else None
337
+ p._cookies = _copy_cookie_jar(self._cookies)
338
+ p.body = self.body
339
+ p.hooks = self.hooks
340
+ p._body_position = self._body_position
341
+ return p
342
+
343
+ def prepare_method(self, method):
344
+ """Prepares the given HTTP method."""
345
+ self.method = method
346
+ if self.method is not None:
347
+ self.method = to_native_string(self.method.upper())
348
+
349
+ @staticmethod
350
+ def _get_idna_encoded_host(host):
351
+ import idna
352
+
353
+ try:
354
+ host = idna.encode(host, uts46=True).decode('utf-8')
355
+ except idna.IDNAError:
356
+ raise UnicodeError
357
+ return host
358
+
359
+ def prepare_url(self, url, params):
360
+ """Prepares the given HTTP URL."""
361
+ #: Accept objects that have string representations.
362
+ #: We're unable to blindly call unicode/str functions
363
+ #: as this will include the bytestring indicator (b'')
364
+ #: on python 3.x.
365
+ #: https://github.com/requests/requests/pull/2238
366
+ if isinstance(url, bytes):
367
+ url = url.decode('utf8')
368
+ else:
369
+ url = unicode(url) if is_py2 else str(url)
370
+
371
+ # Remove leading whitespaces from url
372
+ url = url.lstrip()
373
+
374
+ # Don't do any URL preparation for non-HTTP schemes like `mailto`,
375
+ # `data` etc to work around exceptions from `url_parse`, which
376
+ # handles RFC 3986 only.
377
+ if ':' in url and not url.lower().startswith('http'):
378
+ self.url = url
379
+ return
380
+
381
+ # Support for unicode domain names and paths.
382
+ try:
383
+ scheme, auth, host, port, path, query, fragment = parse_url(url)
384
+ except LocationParseError as e:
385
+ raise InvalidURL(*e.args)
386
+
387
+ if not scheme:
388
+ error = ("Invalid URL {0!r}: No schema supplied. Perhaps you meant http://{0}?")
389
+ error = error.format(to_native_string(url, 'utf8'))
390
+
391
+ raise MissingSchema(error)
392
+
393
+ if not host:
394
+ raise InvalidURL("Invalid URL %r: No host supplied" % url)
395
+
396
+ # In general, we want to try IDNA encoding the hostname if the string contains
397
+ # non-ASCII characters. This allows users to automatically get the correct IDNA
398
+ # behaviour. For strings containing only ASCII characters, we need to also verify
399
+ # it doesn't start with a wildcard (*), before allowing the unencoded hostname.
400
+ if not unicode_is_ascii(host):
401
+ try:
402
+ host = self._get_idna_encoded_host(host)
403
+ except UnicodeError:
404
+ raise InvalidURL('URL has an invalid label.')
405
+ elif host.startswith(u'*'):
406
+ raise InvalidURL('URL has an invalid label.')
407
+
408
+ # Carefully reconstruct the network location
409
+ netloc = auth or ''
410
+ if netloc:
411
+ netloc += '@'
412
+ netloc += host
413
+ if port:
414
+ netloc += ':' + str(port)
415
+
416
+ # Bare domains aren't valid URLs.
417
+ if not path:
418
+ path = '/'
419
+
420
+ if is_py2:
421
+ if isinstance(scheme, str):
422
+ scheme = scheme.encode('utf-8')
423
+ if isinstance(netloc, str):
424
+ netloc = netloc.encode('utf-8')
425
+ if isinstance(path, str):
426
+ path = path.encode('utf-8')
427
+ if isinstance(query, str):
428
+ query = query.encode('utf-8')
429
+ if isinstance(fragment, str):
430
+ fragment = fragment.encode('utf-8')
431
+
432
+ if isinstance(params, (str, bytes)):
433
+ params = to_native_string(params)
434
+
435
+ enc_params = self._encode_params(params)
436
+ if enc_params:
437
+ if query:
438
+ query = '%s&%s' % (query, enc_params)
439
+ else:
440
+ query = enc_params
441
+
442
+ url = requote_uri(urlunparse([scheme, netloc, path, None, query, fragment]))
443
+ self.url = url
444
+
445
+ def prepare_headers(self, headers):
446
+ """Prepares the given HTTP headers."""
447
+
448
+ self.headers = CaseInsensitiveDict()
449
+ if headers:
450
+ for header in headers.items():
451
+ # Raise exception on invalid header value.
452
+ check_header_validity(header)
453
+ name, value = header
454
+ self.headers[to_native_string(name)] = value
455
+
456
+ def prepare_body(self, data, files, json=None):
457
+ """Prepares the given HTTP body data."""
458
+
459
+ # Check if file, fo, generator, iterator.
460
+ # If not, run through normal process.
461
+
462
+ # Nottin' on you.
463
+ body = None
464
+ content_type = None
465
+
466
+ if not data and json is not None:
467
+ # urllib3 requires a bytes-like body. Python 2's json.dumps
468
+ # provides this natively, but Python 3 gives a Unicode string.
469
+ content_type = 'application/json'
470
+ body = complexjson.dumps(json)
471
+ if not isinstance(body, bytes):
472
+ body = body.encode('utf-8')
473
+
474
+ is_stream = all([
475
+ hasattr(data, '__iter__'),
476
+ not isinstance(data, (basestring, list, tuple, Mapping))
477
+ ])
478
+
479
+ try:
480
+ length = super_len(data)
481
+ except (TypeError, AttributeError, UnsupportedOperation):
482
+ length = None
483
+
484
+ if is_stream:
485
+ body = data
486
+
487
+ if getattr(body, 'tell', None) is not None:
488
+ # Record the current file position before reading.
489
+ # This will allow us to rewind a file in the event
490
+ # of a redirect.
491
+ try:
492
+ self._body_position = body.tell()
493
+ except (IOError, OSError):
494
+ # This differentiates from None, allowing us to catch
495
+ # a failed `tell()` later when trying to rewind the body
496
+ self._body_position = object()
497
+
498
+ if files:
499
+ raise NotImplementedError('Streamed bodies and files are mutually exclusive.')
500
+
501
+ if length:
502
+ self.headers['Content-Length'] = builtin_str(length)
503
+ else:
504
+ self.headers['Transfer-Encoding'] = 'chunked'
505
+ else:
506
+ # Multi-part file uploads.
507
+ if files:
508
+ (body, content_type) = self._encode_files(files, data)
509
+ else:
510
+ if data:
511
+ body = self._encode_params(data)
512
+ if isinstance(data, basestring) or hasattr(data, 'read'):
513
+ content_type = None
514
+ else:
515
+ content_type = 'application/x-www-form-urlencoded'
516
+
517
+ self.prepare_content_length(body)
518
+
519
+ # Add content-type if it wasn't explicitly provided.
520
+ if content_type and ('content-type' not in self.headers):
521
+ self.headers['Content-Type'] = content_type
522
+
523
+ self.body = body
524
+
525
+ def prepare_content_length(self, body):
526
+ """Prepare Content-Length header based on request method and body"""
527
+ if body is not None:
528
+ length = super_len(body)
529
+ if length:
530
+ # If length exists, set it. Otherwise, we fallback
531
+ # to Transfer-Encoding: chunked.
532
+ self.headers['Content-Length'] = builtin_str(length)
533
+ elif self.method not in ('GET', 'HEAD') and self.headers.get('Content-Length') is None:
534
+ # Set Content-Length to 0 for methods that can have a body
535
+ # but don't provide one. (i.e. not GET or HEAD)
536
+ self.headers['Content-Length'] = '0'
537
+
538
+ def prepare_auth(self, auth, url=''):
539
+ """Prepares the given HTTP auth data."""
540
+
541
+ # If no Auth is explicitly provided, extract it from the URL first.
542
+ if auth is None:
543
+ url_auth = get_auth_from_url(self.url)
544
+ auth = url_auth if any(url_auth) else None
545
+
546
+ if auth:
547
+ if isinstance(auth, tuple) and len(auth) == 2:
548
+ # special-case basic HTTP auth
549
+ auth = HTTPBasicAuth(*auth)
550
+
551
+ # Allow auth to make its changes.
552
+ r = auth(self)
553
+
554
+ # Update self to reflect the auth changes.
555
+ self.__dict__.update(r.__dict__)
556
+
557
+ # Recompute Content-Length
558
+ self.prepare_content_length(self.body)
559
+
560
+ def prepare_cookies(self, cookies):
561
+ """Prepares the given HTTP cookie data.
562
+
563
+ This function eventually generates a ``Cookie`` header from the
564
+ given cookies using cookielib. Due to cookielib's design, the header
565
+ will not be regenerated if it already exists, meaning this function
566
+ can only be called once for the life of the
567
+ :class:`PreparedRequest <PreparedRequest>` object. Any subsequent calls
568
+ to ``prepare_cookies`` will have no actual effect, unless the "Cookie"
569
+ header is removed beforehand.
570
+ """
571
+ if isinstance(cookies, cookielib.CookieJar):
572
+ self._cookies = cookies
573
+ else:
574
+ self._cookies = cookiejar_from_dict(cookies)
575
+
576
+ cookie_header = get_cookie_header(self._cookies, self)
577
+ if cookie_header is not None:
578
+ self.headers['Cookie'] = cookie_header
579
+
580
+ def prepare_hooks(self, hooks):
581
+ """Prepares the given hooks."""
582
+ # hooks can be passed as None to the prepare method and to this
583
+ # method. To prevent iterating over None, simply use an empty list
584
+ # if hooks is False-y
585
+ hooks = hooks or []
586
+ for event in hooks:
587
+ self.register_hook(event, hooks[event])
588
+
589
+
590
+ class Response(object):
591
+ """The :class:`Response <Response>` object, which contains a
592
+ server's response to an HTTP request.
593
+ """
594
+
595
+ __attrs__ = [
596
+ '_content', 'status_code', 'headers', 'url', 'history',
597
+ 'encoding', 'reason', 'cookies', 'elapsed', 'request'
598
+ ]
599
+
600
+ def __init__(self):
601
+ self._content = False
602
+ self._content_consumed = False
603
+ self._next = None
604
+
605
+ #: Integer Code of responded HTTP Status, e.g. 404 or 200.
606
+ self.status_code = None
607
+
608
+ #: Case-insensitive Dictionary of Response Headers.
609
+ #: For example, ``headers['content-encoding']`` will return the
610
+ #: value of a ``'Content-Encoding'`` response header.
611
+ self.headers = CaseInsensitiveDict()
612
+
613
+ #: File-like object representation of response (for advanced usage).
614
+ #: Use of ``raw`` requires that ``stream=True`` be set on the request.
615
+ # This requirement does not apply for use internally to Requests.
616
+ self.raw = None
617
+
618
+ #: Final URL location of Response.
619
+ self.url = None
620
+
621
+ #: Encoding to decode with when accessing r.text.
622
+ self.encoding = None
623
+
624
+ #: A list of :class:`Response <Response>` objects from
625
+ #: the history of the Request. Any redirect responses will end
626
+ #: up here. The list is sorted from the oldest to the most recent request.
627
+ self.history = []
628
+
629
+ #: Textual reason of responded HTTP Status, e.g. "Not Found" or "OK".
630
+ self.reason = None
631
+
632
+ #: A CookieJar of Cookies the server sent back.
633
+ self.cookies = cookiejar_from_dict({})
634
+
635
+ #: The amount of time elapsed between sending the request
636
+ #: and the arrival of the response (as a timedelta).
637
+ #: This property specifically measures the time taken between sending
638
+ #: the first byte of the request and finishing parsing the headers. It
639
+ #: is therefore unaffected by consuming the response content or the
640
+ #: value of the ``stream`` keyword argument.
641
+ self.elapsed = datetime.timedelta(0)
642
+
643
+ #: The :class:`PreparedRequest <PreparedRequest>` object to which this
644
+ #: is a response.
645
+ self.request = None
646
+
647
+ def __enter__(self):
648
+ return self
649
+
650
+ def __exit__(self, *args):
651
+ self.close()
652
+
653
+ def __getstate__(self):
654
+ # Consume everything; accessing the content attribute makes
655
+ # sure the content has been fully read.
656
+ if not self._content_consumed:
657
+ self.content
658
+
659
+ return dict(
660
+ (attr, getattr(self, attr, None))
661
+ for attr in self.__attrs__
662
+ )
663
+
664
+ def __setstate__(self, state):
665
+ for name, value in state.items():
666
+ setattr(self, name, value)
667
+
668
+ # pickled objects do not have .raw
669
+ setattr(self, '_content_consumed', True)
670
+ setattr(self, 'raw', None)
671
+
672
+ def __repr__(self):
673
+ return '<Response [%s]>' % (self.status_code)
674
+
675
+ def __bool__(self):
676
+ """Returns True if :attr:`status_code` is less than 400.
677
+
678
+ This attribute checks if the status code of the response is between
679
+ 400 and 600 to see if there was a client error or a server error. If
680
+ the status code, is between 200 and 400, this will return True. This
681
+ is **not** a check to see if the response code is ``200 OK``.
682
+ """
683
+ return self.ok
684
+
685
+ def __nonzero__(self):
686
+ """Returns True if :attr:`status_code` is less than 400.
687
+
688
+ This attribute checks if the status code of the response is between
689
+ 400 and 600 to see if there was a client error or a server error. If
690
+ the status code, is between 200 and 400, this will return True. This
691
+ is **not** a check to see if the response code is ``200 OK``.
692
+ """
693
+ return self.ok
694
+
695
+ def __iter__(self):
696
+ """Allows you to use a response as an iterator."""
697
+ return self.iter_content(128)
698
+
699
+ @property
700
+ def ok(self):
701
+ """Returns True if :attr:`status_code` is less than 400.
702
+
703
+ This attribute checks if the status code of the response is between
704
+ 400 and 600 to see if there was a client error or a server error. If
705
+ the status code, is between 200 and 400, this will return True. This
706
+ is **not** a check to see if the response code is ``200 OK``.
707
+ """
708
+ try:
709
+ self.raise_for_status()
710
+ except HTTPError:
711
+ return False
712
+ return True
713
+
714
+ @property
715
+ def is_redirect(self):
716
+ """True if this Response is a well-formed HTTP redirect that could have
717
+ been processed automatically (by :meth:`Session.resolve_redirects`).
718
+ """
719
+ return ('location' in self.headers and self.status_code in REDIRECT_STATI)
720
+
721
+ @property
722
+ def is_permanent_redirect(self):
723
+ """True if this Response one of the permanent versions of redirect."""
724
+ return ('location' in self.headers and self.status_code in (codes.moved_permanently, codes.permanent_redirect))
725
+
726
+ @property
727
+ def next(self):
728
+ """Returns a PreparedRequest for the next request in a redirect chain, if there is one."""
729
+ return self._next
730
+
731
+ @property
732
+ def apparent_encoding(self):
733
+ """The apparent encoding, provided by the chardet library."""
734
+ return chardet.detect(self.content)['encoding']
735
+
736
+ def iter_content(self, chunk_size=1, decode_unicode=False):
737
+ """Iterates over the response data. When stream=True is set on the
738
+ request, this avoids reading the content at once into memory for
739
+ large responses. The chunk size is the number of bytes it should
740
+ read into memory. This is not necessarily the length of each item
741
+ returned as decoding can take place.
742
+
743
+ chunk_size must be of type int or None. A value of None will
744
+ function differently depending on the value of `stream`.
745
+ stream=True will read data as it arrives in whatever size the
746
+ chunks are received. If stream=False, data is returned as
747
+ a single chunk.
748
+
749
+ If decode_unicode is True, content will be decoded using the best
750
+ available encoding based on the response.
751
+ """
752
+
753
+ def generate():
754
+ # Special case for urllib3.
755
+ if hasattr(self.raw, 'stream'):
756
+ try:
757
+ for chunk in self.raw.stream(chunk_size, decode_content=True):
758
+ yield chunk
759
+ except ProtocolError as e:
760
+ raise ChunkedEncodingError(e)
761
+ except DecodeError as e:
762
+ raise ContentDecodingError(e)
763
+ except ReadTimeoutError as e:
764
+ raise ConnectionError(e)
765
+ else:
766
+ # Standard file-like object.
767
+ while True:
768
+ chunk = self.raw.read(chunk_size)
769
+ if not chunk:
770
+ break
771
+ yield chunk
772
+
773
+ self._content_consumed = True
774
+
775
+ if self._content_consumed and isinstance(self._content, bool):
776
+ raise StreamConsumedError()
777
+ elif chunk_size is not None and not isinstance(chunk_size, int):
778
+ raise TypeError("chunk_size must be an int, it is instead a %s." % type(chunk_size))
779
+ # simulate reading small chunks of the content
780
+ reused_chunks = iter_slices(self._content, chunk_size)
781
+
782
+ stream_chunks = generate()
783
+
784
+ chunks = reused_chunks if self._content_consumed else stream_chunks
785
+
786
+ if decode_unicode:
787
+ chunks = stream_decode_response_unicode(chunks, self)
788
+
789
+ return chunks
790
+
791
+ def iter_lines(self, chunk_size=ITER_CHUNK_SIZE, decode_unicode=None, delimiter=None):
792
+ """Iterates over the response data, one line at a time. When
793
+ stream=True is set on the request, this avoids reading the
794
+ content at once into memory for large responses.
795
+
796
+ .. note:: This method is not reentrant safe.
797
+ """
798
+
799
+ pending = None
800
+
801
+ for chunk in self.iter_content(chunk_size=chunk_size, decode_unicode=decode_unicode):
802
+
803
+ if pending is not None:
804
+ chunk = pending + chunk
805
+
806
+ if delimiter:
807
+ lines = chunk.split(delimiter)
808
+ else:
809
+ lines = chunk.splitlines()
810
+
811
+ if lines and lines[-1] and chunk and lines[-1][-1] == chunk[-1]:
812
+ pending = lines.pop()
813
+ else:
814
+ pending = None
815
+
816
+ for line in lines:
817
+ yield line
818
+
819
+ if pending is not None:
820
+ yield pending
821
+
822
+ @property
823
+ def content(self):
824
+ """Content of the response, in bytes."""
825
+
826
+ if self._content is False:
827
+ # Read the contents.
828
+ if self._content_consumed:
829
+ raise RuntimeError(
830
+ 'The content for this response was already consumed')
831
+
832
+ if self.status_code == 0 or self.raw is None:
833
+ self._content = None
834
+ else:
835
+ self._content = bytes().join(self.iter_content(CONTENT_CHUNK_SIZE)) or bytes()
836
+
837
+ self._content_consumed = True
838
+ # don't need to release the connection; that's been handled by urllib3
839
+ # since we exhausted the data.
840
+ return self._content
841
+
842
+ @property
843
+ def text(self):
844
+ """Content of the response, in unicode.
845
+
846
+ If Response.encoding is None, encoding will be guessed using
847
+ ``chardet``.
848
+
849
+ The encoding of the response content is determined based solely on HTTP
850
+ headers, following RFC 2616 to the letter. If you can take advantage of
851
+ non-HTTP knowledge to make a better guess at the encoding, you should
852
+ set ``r.encoding`` appropriately before accessing this property.
853
+ """
854
+
855
+ # Try charset from content-type
856
+ content = None
857
+ encoding = self.encoding
858
+
859
+ if not self.content:
860
+ return str('')
861
+
862
+ # Fallback to auto-detected encoding.
863
+ if self.encoding is None:
864
+ encoding = self.apparent_encoding
865
+
866
+ # Decode unicode from given encoding.
867
+ try:
868
+ content = str(self.content, encoding, errors='replace')
869
+ except (LookupError, TypeError):
870
+ # A LookupError is raised if the encoding was not found which could
871
+ # indicate a misspelling or similar mistake.
872
+ #
873
+ # A TypeError can be raised if encoding is None
874
+ #
875
+ # So we try blindly encoding.
876
+ content = str(self.content, errors='replace')
877
+
878
+ return content
879
+
880
+ def json(self, **kwargs):
881
+ r"""Returns the json-encoded content of a response, if any.
882
+
883
+ :param \*\*kwargs: Optional arguments that ``json.loads`` takes.
884
+ :raises ValueError: If the response body does not contain valid json.
885
+ """
886
+
887
+ if not self.encoding and self.content and len(self.content) > 3:
888
+ # No encoding set. JSON RFC 4627 section 3 states we should expect
889
+ # UTF-8, -16 or -32. Detect which one to use; If the detection or
890
+ # decoding fails, fall back to `self.text` (using chardet to make
891
+ # a best guess).
892
+ encoding = guess_json_utf(self.content)
893
+ if encoding is not None:
894
+ try:
895
+ return complexjson.loads(
896
+ self.content.decode(encoding), **kwargs
897
+ )
898
+ except UnicodeDecodeError:
899
+ # Wrong UTF codec detected; usually because it's not UTF-8
900
+ # but some other 8-bit codec. This is an RFC violation,
901
+ # and the server didn't bother to tell us what codec *was*
902
+ # used.
903
+ pass
904
+ return complexjson.loads(self.text, **kwargs)
905
+
906
+ @property
907
+ def links(self):
908
+ """Returns the parsed header links of the response, if any."""
909
+
910
+ header = self.headers.get('link')
911
+
912
+ # l = MultiDict()
913
+ l = {}
914
+
915
+ if header:
916
+ links = parse_header_links(header)
917
+
918
+ for link in links:
919
+ key = link.get('rel') or link.get('url')
920
+ l[key] = link
921
+
922
+ return l
923
+
924
+ def raise_for_status(self):
925
+ """Raises stored :class:`HTTPError`, if one occurred."""
926
+
927
+ http_error_msg = ''
928
+ if isinstance(self.reason, bytes):
929
+ # We attempt to decode utf-8 first because some servers
930
+ # choose to localize their reason strings. If the string
931
+ # isn't utf-8, we fall back to iso-8859-1 for all other
932
+ # encodings. (See PR #3538)
933
+ try:
934
+ reason = self.reason.decode('utf-8')
935
+ except UnicodeDecodeError:
936
+ reason = self.reason.decode('iso-8859-1')
937
+ else:
938
+ reason = self.reason
939
+
940
+ if 400 <= self.status_code < 500:
941
+ http_error_msg = u'%s Client Error: %s for url: %s' % (self.status_code, reason, self.url)
942
+
943
+ elif 500 <= self.status_code < 600:
944
+ http_error_msg = u'%s Server Error: %s for url: %s' % (self.status_code, reason, self.url)
945
+
946
+ if http_error_msg:
947
+ raise HTTPError(http_error_msg, response=self)
948
+
949
+ def close(self):
950
+ """Releases the connection back to the pool. Once this method has been
951
+ called the underlying ``raw`` object must not be accessed again.
952
+
953
+ *Note: Should not normally need to be called explicitly.*
954
+ """
955
+ if not self._content_consumed:
956
+ self.raw.close()
957
+
958
+ release_conn = getattr(self.raw, 'release_conn', None)
959
+ if release_conn is not None:
960
+ release_conn()