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,910 @@
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
+ from __future__ import absolute_import
16
+ import errno
17
+ import logging
18
+ import sys
19
+ import warnings
20
+
21
+ from socket import error as SocketError, timeout as SocketTimeout
22
+ import socket
23
+
24
+
25
+ from .exceptions import (
26
+ ClosedPoolError,
27
+ ProtocolError,
28
+ EmptyPoolError,
29
+ HeaderParsingError,
30
+ HostChangedError,
31
+ LocationValueError,
32
+ MaxRetryError,
33
+ ProxyError,
34
+ ReadTimeoutError,
35
+ SSLError,
36
+ TimeoutError,
37
+ InsecureRequestWarning,
38
+ NewConnectionError,
39
+ )
40
+ from .packages.ssl_match_hostname import CertificateError
41
+ from .packages import six
42
+ from .packages.six.moves import queue
43
+ from .connection import (
44
+ port_by_scheme,
45
+ DummyConnection,
46
+ HTTPConnection, HTTPSConnection, VerifiedHTTPSConnection,
47
+ HTTPException, BaseSSLError,
48
+ )
49
+ from .request import RequestMethods
50
+ from .response import HTTPResponse
51
+
52
+ from .util.connection import is_connection_dropped
53
+ from .util.request import set_file_position
54
+ from .util.response import assert_header_parsing
55
+ from .util.retry import Retry
56
+ from .util.timeout import Timeout
57
+ from .util.url import get_host, Url, NORMALIZABLE_SCHEMES
58
+ from .util.queue import LifoQueue
59
+
60
+
61
+ xrange = six.moves.xrange
62
+
63
+ log = logging.getLogger(__name__)
64
+
65
+ _Default = object()
66
+
67
+
68
+ # Pool objects
69
+ class ConnectionPool(object):
70
+ """
71
+ Base class for all connection pools, such as
72
+ :class:`.HTTPConnectionPool` and :class:`.HTTPSConnectionPool`.
73
+ """
74
+
75
+ scheme = None
76
+ QueueCls = LifoQueue
77
+
78
+ def __init__(self, host, port=None):
79
+ if not host:
80
+ raise LocationValueError("No host specified.")
81
+
82
+ self.host = _ipv6_host(host, self.scheme)
83
+ self._proxy_host = host.lower()
84
+ self.port = port
85
+
86
+ def __str__(self):
87
+ return '%s(host=%r, port=%r)' % (type(self).__name__,
88
+ self.host, self.port)
89
+
90
+ def __enter__(self):
91
+ return self
92
+
93
+ def __exit__(self, exc_type, exc_val, exc_tb):
94
+ self.close()
95
+ # Return False to re-raise any potential exceptions
96
+ return False
97
+
98
+ def close(self):
99
+ """
100
+ Close all pooled connections and disable the pool.
101
+ """
102
+ pass
103
+
104
+
105
+ # This is taken from http://hg.python.org/cpython/file/7aaba721ebc0/Lib/socket.py#l252
106
+ _blocking_errnos = {errno.EAGAIN, errno.EWOULDBLOCK}
107
+
108
+
109
+ class HTTPConnectionPool(ConnectionPool, RequestMethods):
110
+ """
111
+ Thread-safe connection pool for one host.
112
+
113
+ :param host:
114
+ Host used for this HTTP Connection (e.g. "localhost"), passed into
115
+ :class:`httplib.HTTPConnection`.
116
+
117
+ :param port:
118
+ Port used for this HTTP Connection (None is equivalent to 80), passed
119
+ into :class:`httplib.HTTPConnection`.
120
+
121
+ :param strict:
122
+ Causes BadStatusLine to be raised if the status line can't be parsed
123
+ as a valid HTTP/1.0 or 1.1 status line, passed into
124
+ :class:`httplib.HTTPConnection`.
125
+
126
+ .. note::
127
+ Only works in Python 2. This parameter is ignored in Python 3.
128
+
129
+ :param timeout:
130
+ Socket timeout in seconds for each individual connection. This can
131
+ be a float or integer, which sets the timeout for the HTTP request,
132
+ or an instance of :class:`urllib3.util.Timeout` which gives you more
133
+ fine-grained control over request timeouts. After the constructor has
134
+ been parsed, this is always a `urllib3.util.Timeout` object.
135
+
136
+ :param maxsize:
137
+ Number of connections to save that can be reused. More than 1 is useful
138
+ in multithreaded situations. If ``block`` is set to False, more
139
+ connections will be created but they will not be saved once they've
140
+ been used.
141
+
142
+ :param block:
143
+ If set to True, no more than ``maxsize`` connections will be used at
144
+ a time. When no free connections are available, the call will block
145
+ until a connection has been released. This is a useful side effect for
146
+ particular multithreaded situations where one does not want to use more
147
+ than maxsize connections per host to prevent flooding.
148
+
149
+ :param headers:
150
+ Headers to include with all requests, unless other headers are given
151
+ explicitly.
152
+
153
+ :param retries:
154
+ Retry configuration to use by default with requests in this pool.
155
+
156
+ :param _proxy:
157
+ Parsed proxy URL, should not be used directly, instead, see
158
+ :class:`urllib3.connectionpool.ProxyManager`"
159
+
160
+ :param _proxy_headers:
161
+ A dictionary with proxy headers, should not be used directly,
162
+ instead, see :class:`urllib3.connectionpool.ProxyManager`"
163
+
164
+ :param \\**conn_kw:
165
+ Additional parameters are used to create fresh :class:`urllib3.connection.HTTPConnection`,
166
+ :class:`urllib3.connection.HTTPSConnection` instances.
167
+ """
168
+
169
+ scheme = 'http'
170
+ ConnectionCls = HTTPConnection
171
+ ResponseCls = HTTPResponse
172
+
173
+ def __init__(self, host, port=None, strict=False,
174
+ timeout=Timeout.DEFAULT_TIMEOUT, maxsize=1, block=False,
175
+ headers=None, retries=None,
176
+ _proxy=None, _proxy_headers=None,
177
+ **conn_kw):
178
+ ConnectionPool.__init__(self, host, port)
179
+ RequestMethods.__init__(self, headers)
180
+
181
+ self.strict = strict
182
+
183
+ if not isinstance(timeout, Timeout):
184
+ timeout = Timeout.from_float(timeout)
185
+
186
+ if retries is None:
187
+ retries = Retry.DEFAULT
188
+
189
+ self.timeout = timeout
190
+ self.retries = retries
191
+
192
+ self.pool = self.QueueCls(maxsize)
193
+ self.block = block
194
+
195
+ self.proxy = _proxy
196
+ self.proxy_headers = _proxy_headers or {}
197
+
198
+ # Fill the queue up so that doing get() on it will block properly
199
+ for _ in xrange(maxsize):
200
+ self.pool.put(None)
201
+
202
+ # These are mostly for testing and debugging purposes.
203
+ self.num_connections = 0
204
+ self.num_requests = 0
205
+ self.conn_kw = conn_kw
206
+
207
+ if self.proxy:
208
+ # Enable Nagle's algorithm for proxies, to avoid packet fragmentation.
209
+ # We cannot know if the user has added default socket options, so we cannot replace the
210
+ # list.
211
+ self.conn_kw.setdefault('socket_options', [])
212
+
213
+ def _new_conn(self):
214
+ """
215
+ Return a fresh :class:`HTTPConnection`.
216
+ """
217
+ self.num_connections += 1
218
+ log.debug("Starting new HTTP connection (%d): %s:%s",
219
+ self.num_connections, self.host, self.port or "80")
220
+
221
+ conn = self.ConnectionCls(host=self.host, port=self.port,
222
+ timeout=self.timeout.connect_timeout,
223
+ strict=self.strict, **self.conn_kw)
224
+ return conn
225
+
226
+ def _get_conn(self, timeout=None):
227
+ """
228
+ Get a connection. Will return a pooled connection if one is available.
229
+
230
+ If no connections are available and :prop:`.block` is ``False``, then a
231
+ fresh connection is returned.
232
+
233
+ :param timeout:
234
+ Seconds to wait before giving up and raising
235
+ :class:`urllib3.exceptions.EmptyPoolError` if the pool is empty and
236
+ :prop:`.block` is ``True``.
237
+ """
238
+ conn = None
239
+ try:
240
+ conn = self.pool.get(block=self.block, timeout=timeout)
241
+
242
+ except AttributeError: # self.pool is None
243
+ raise ClosedPoolError(self, "Pool is closed.")
244
+
245
+ except queue.Empty:
246
+ if self.block:
247
+ raise EmptyPoolError(self,
248
+ "Pool reached maximum size and no more "
249
+ "connections are allowed.")
250
+ pass # Oh well, we'll create a new connection then
251
+
252
+ # If this is a persistent connection, check if it got disconnected
253
+ if conn and is_connection_dropped(conn):
254
+ log.debug("Resetting dropped connection: %s", self.host)
255
+ conn.close()
256
+ if getattr(conn, 'auto_open', 1) == 0:
257
+ # This is a proxied connection that has been mutated by
258
+ # httplib._tunnel() and cannot be reused (since it would
259
+ # attempt to bypass the proxy)
260
+ conn = None
261
+
262
+ return conn or self._new_conn()
263
+
264
+ def _put_conn(self, conn):
265
+ """
266
+ Put a connection back into the pool.
267
+
268
+ :param conn:
269
+ Connection object for the current host and port as returned by
270
+ :meth:`._new_conn` or :meth:`._get_conn`.
271
+
272
+ If the pool is already full, the connection is closed and discarded
273
+ because we exceeded maxsize. If connections are discarded frequently,
274
+ then maxsize should be increased.
275
+
276
+ If the pool is closed, then the connection will be closed and discarded.
277
+ """
278
+ try:
279
+ self.pool.put(conn, block=False)
280
+ return # Everything is dandy, done.
281
+ except AttributeError:
282
+ # self.pool is None.
283
+ pass
284
+ except queue.Full:
285
+ # This should never happen if self.block == True
286
+ log.warning(
287
+ "Connection pool is full, discarding connection: %s",
288
+ self.host)
289
+
290
+ # Connection never got put back into the pool, close it.
291
+ if conn:
292
+ conn.close()
293
+
294
+ def _validate_conn(self, conn):
295
+ """
296
+ Called right before a request is made, after the socket is created.
297
+ """
298
+ pass
299
+
300
+ def _prepare_proxy(self, conn):
301
+ # Nothing to do for HTTP connections.
302
+ pass
303
+
304
+ def _get_timeout(self, timeout):
305
+ """ Helper that always returns a :class:`urllib3.util.Timeout` """
306
+ if timeout is _Default:
307
+ return self.timeout.clone()
308
+
309
+ if isinstance(timeout, Timeout):
310
+ return timeout.clone()
311
+ else:
312
+ # User passed us an int/float. This is for backwards compatibility,
313
+ # can be removed later
314
+ return Timeout.from_float(timeout)
315
+
316
+ def _raise_timeout(self, err, url, timeout_value):
317
+ """Is the error actually a timeout? Will raise a ReadTimeout or pass"""
318
+
319
+ if isinstance(err, SocketTimeout):
320
+ raise ReadTimeoutError(self, url, "Read timed out. (read timeout=%s)" % timeout_value)
321
+
322
+ # See the above comment about EAGAIN in Python 3. In Python 2 we have
323
+ # to specifically catch it and throw the timeout error
324
+ if hasattr(err, 'errno') and err.errno in _blocking_errnos:
325
+ raise ReadTimeoutError(self, url, "Read timed out. (read timeout=%s)" % timeout_value)
326
+
327
+ # Catch possible read timeouts thrown as SSL errors. If not the
328
+ # case, rethrow the original. We need to do this because of:
329
+ # http://bugs.python.org/issue10272
330
+ if 'timed out' in str(err) or 'did not complete (read)' in str(err): # Python < 2.7.4
331
+ raise ReadTimeoutError(self, url, "Read timed out. (read timeout=%s)" % timeout_value)
332
+
333
+ def _make_request(self, conn, method, url, timeout=_Default, chunked=False,
334
+ **httplib_request_kw):
335
+ """
336
+ Perform a request on a given urllib connection object taken from our
337
+ pool.
338
+
339
+ :param conn:
340
+ a connection from one of our connection pools
341
+
342
+ :param timeout:
343
+ Socket timeout in seconds for the request. This can be a
344
+ float or integer, which will set the same timeout value for
345
+ the socket connect and the socket read, or an instance of
346
+ :class:`urllib3.util.Timeout`, which gives you more fine-grained
347
+ control over your timeouts.
348
+ """
349
+ self.num_requests += 1
350
+
351
+ timeout_obj = self._get_timeout(timeout)
352
+ timeout_obj.start_connect()
353
+ conn.timeout = timeout_obj.connect_timeout
354
+
355
+ # Trigger any extra validation we need to do.
356
+ try:
357
+ self._validate_conn(conn)
358
+ except (SocketTimeout, BaseSSLError) as e:
359
+ # Py2 raises this as a BaseSSLError, Py3 raises it as socket timeout.
360
+ self._raise_timeout(err=e, url=url, timeout_value=conn.timeout)
361
+ raise
362
+
363
+ # conn.request() calls httplib.*.request, not the method in
364
+ # urllib3.request. It also calls makefile (recv) on the socket.
365
+ if chunked:
366
+ conn.request_chunked(method, url, **httplib_request_kw)
367
+ else:
368
+ conn.request(method, url, **httplib_request_kw)
369
+
370
+ # Reset the timeout for the recv() on the socket
371
+ read_timeout = timeout_obj.read_timeout
372
+
373
+ # App Engine doesn't have a sock attr
374
+ if getattr(conn, 'sock', None):
375
+ # In Python 3 socket.py will catch EAGAIN and return None when you
376
+ # try and read into the file pointer created by http.client, which
377
+ # instead raises a BadStatusLine exception. Instead of catching
378
+ # the exception and assuming all BadStatusLine exceptions are read
379
+ # timeouts, check for a zero timeout before making the request.
380
+ if read_timeout == 0:
381
+ raise ReadTimeoutError(
382
+ self, url, "Read timed out. (read timeout=%s)" % read_timeout)
383
+ if read_timeout is Timeout.DEFAULT_TIMEOUT:
384
+ conn.sock.settimeout(socket.getdefaulttimeout())
385
+ else: # None or a value
386
+ conn.sock.settimeout(read_timeout)
387
+
388
+ # Receive the response from the server
389
+ try:
390
+ try: # Python 2.7, use buffering of HTTP responses
391
+ httplib_response = conn.getresponse(buffering=True)
392
+ except TypeError: # Python 3
393
+ try:
394
+ httplib_response = conn.getresponse()
395
+ except Exception as e:
396
+ # Remove the TypeError from the exception chain in Python 3;
397
+ # otherwise it looks like a programming error was the cause.
398
+ six.raise_from(e, None)
399
+ except (SocketTimeout, BaseSSLError, SocketError) as e:
400
+ self._raise_timeout(err=e, url=url, timeout_value=read_timeout)
401
+ raise
402
+
403
+ # AppEngine doesn't have a version attr.
404
+ http_version = getattr(conn, '_http_vsn_str', 'HTTP/?')
405
+ log.debug("%s://%s:%s \"%s %s %s\" %s %s", self.scheme, self.host, self.port,
406
+ method, url, http_version, httplib_response.status,
407
+ httplib_response.length)
408
+
409
+ try:
410
+ assert_header_parsing(httplib_response.msg)
411
+ except (HeaderParsingError, TypeError) as hpe: # Platform-specific: Python 3
412
+ log.warning(
413
+ 'Failed to parse headers (url=%s): %s',
414
+ self._absolute_url(url), hpe, exc_info=True)
415
+
416
+ return httplib_response
417
+
418
+ def _absolute_url(self, path):
419
+ return Url(scheme=self.scheme, host=self.host, port=self.port, path=path).url
420
+
421
+ def close(self):
422
+ """
423
+ Close all pooled connections and disable the pool.
424
+ """
425
+ if self.pool is None:
426
+ return
427
+ # Disable access to the pool
428
+ old_pool, self.pool = self.pool, None
429
+
430
+ try:
431
+ while True:
432
+ conn = old_pool.get(block=False)
433
+ if conn:
434
+ conn.close()
435
+
436
+ except queue.Empty:
437
+ pass # Done.
438
+
439
+ def is_same_host(self, url):
440
+ """
441
+ Check if the given ``url`` is a member of the same host as this
442
+ connection pool.
443
+ """
444
+ if url.startswith('/'):
445
+ return True
446
+
447
+ # TODO: Add optional support for socket.gethostbyname checking.
448
+ scheme, host, port = get_host(url)
449
+
450
+ host = _ipv6_host(host, self.scheme)
451
+
452
+ # Use explicit default port for comparison when none is given
453
+ if self.port and not port:
454
+ port = port_by_scheme.get(scheme)
455
+ elif not self.port and port == port_by_scheme.get(scheme):
456
+ port = None
457
+
458
+ return (scheme, host, port) == (self.scheme, self.host, self.port)
459
+
460
+ def urlopen(self, method, url, body=None, headers=None, retries=None,
461
+ redirect=True, assert_same_host=True, timeout=_Default,
462
+ pool_timeout=None, release_conn=None, chunked=False,
463
+ body_pos=None, **response_kw):
464
+ """
465
+ Get a connection from the pool and perform an HTTP request. This is the
466
+ lowest level call for making a request, so you'll need to specify all
467
+ the raw details.
468
+
469
+ .. note::
470
+
471
+ More commonly, it's appropriate to use a convenience method provided
472
+ by :class:`.RequestMethods`, such as :meth:`request`.
473
+
474
+ .. note::
475
+
476
+ `release_conn` will only behave as expected if
477
+ `preload_content=False` because we want to make
478
+ `preload_content=False` the default behaviour someday soon without
479
+ breaking backwards compatibility.
480
+
481
+ :param method:
482
+ HTTP request method (such as GET, POST, PUT, etc.)
483
+
484
+ :param body:
485
+ Data to send in the request body (useful for creating
486
+ POST requests, see HTTPConnectionPool.post_url for
487
+ more convenience).
488
+
489
+ :param headers:
490
+ Dictionary of custom headers to send, such as User-Agent,
491
+ If-None-Match, etc. If None, pool headers are used. If provided,
492
+ these headers completely replace any pool-specific headers.
493
+
494
+ :param retries:
495
+ Configure the number of retries to allow before raising a
496
+ :class:`~urllib3.exceptions.MaxRetryError` exception.
497
+
498
+ Pass ``None`` to retry until you receive a response. Pass a
499
+ :class:`~urllib3.util.retry.Retry` object for fine-grained control
500
+ over different types of retries.
501
+ Pass an integer number to retry connection errors that many times,
502
+ but no other types of errors. Pass zero to never retry.
503
+
504
+ If ``False``, then retries are disabled and any exception is raised
505
+ immediately. Also, instead of raising a MaxRetryError on redirects,
506
+ the redirect response will be returned.
507
+
508
+ :type retries: :class:`~urllib3.util.retry.Retry`, False, or an int.
509
+
510
+ :param redirect:
511
+ If True, automatically handle redirects (status codes 301, 302,
512
+ 303, 307, 308). Each redirect counts as a retry. Disabling retries
513
+ will disable redirect, too.
514
+
515
+ :param assert_same_host:
516
+ If ``True``, will make sure that the host of the pool requests is
517
+ consistent else will raise HostChangedError. When False, you can
518
+ use the pool on an HTTP proxy and request foreign hosts.
519
+
520
+ :param timeout:
521
+ If specified, overrides the default timeout for this one
522
+ request. It may be a float (in seconds) or an instance of
523
+ :class:`urllib3.util.Timeout`.
524
+
525
+ :param pool_timeout:
526
+ If set and the pool is set to block=True, then this method will
527
+ block for ``pool_timeout`` seconds and raise EmptyPoolError if no
528
+ connection is available within the time period.
529
+
530
+ :param release_conn:
531
+ If False, then the urlopen call will not release the connection
532
+ back into the pool once a response is received (but will release if
533
+ you read the entire contents of the response such as when
534
+ `preload_content=True`). This is useful if you're not preloading
535
+ the response's content immediately. You will need to call
536
+ ``r.release_conn()`` on the response ``r`` to return the connection
537
+ back into the pool. If None, it takes the value of
538
+ ``response_kw.get('preload_content', True)``.
539
+
540
+ :param chunked:
541
+ If True, urllib3 will send the body using chunked transfer
542
+ encoding. Otherwise, urllib3 will send the body using the standard
543
+ content-length form. Defaults to False.
544
+
545
+ :param int body_pos:
546
+ Position to seek to in file-like body in the event of a retry or
547
+ redirect. Typically this won't need to be set because urllib3 will
548
+ auto-populate the value when needed.
549
+
550
+ :param \\**response_kw:
551
+ Additional parameters are passed to
552
+ :meth:`urllib3.response.HTTPResponse.from_httplib`
553
+ """
554
+ if headers is None:
555
+ headers = self.headers
556
+
557
+ if not isinstance(retries, Retry):
558
+ retries = Retry.from_int(retries, redirect=redirect, default=self.retries)
559
+
560
+ if release_conn is None:
561
+ release_conn = response_kw.get('preload_content', True)
562
+
563
+ # Check host
564
+ if assert_same_host and not self.is_same_host(url):
565
+ raise HostChangedError(self, url, retries)
566
+
567
+ conn = None
568
+
569
+ # Track whether `conn` needs to be released before
570
+ # returning/raising/recursing. Update this variable if necessary, and
571
+ # leave `release_conn` constant throughout the function. That way, if
572
+ # the function recurses, the original value of `release_conn` will be
573
+ # passed down into the recursive call, and its value will be respected.
574
+ #
575
+ # See issue #651 [1] for details.
576
+ #
577
+ # [1] <https://github.com/shazow/urllib3/issues/651>
578
+ release_this_conn = release_conn
579
+
580
+ # Merge the proxy headers. Only do this in HTTP. We have to copy the
581
+ # headers dict so we can safely change it without those changes being
582
+ # reflected in anyone else's copy.
583
+ if self.scheme == 'http':
584
+ headers = headers.copy()
585
+ headers.update(self.proxy_headers)
586
+
587
+ # Must keep the exception bound to a separate variable or else Python 3
588
+ # complains about UnboundLocalError.
589
+ err = None
590
+
591
+ # Keep track of whether we cleanly exited the except block. This
592
+ # ensures we do proper cleanup in finally.
593
+ clean_exit = False
594
+
595
+ # Rewind body position, if needed. Record current position
596
+ # for future rewinds in the event of a redirect/retry.
597
+ body_pos = set_file_position(body, body_pos)
598
+
599
+ try:
600
+ # Request a connection from the queue.
601
+ timeout_obj = self._get_timeout(timeout)
602
+ conn = self._get_conn(timeout=pool_timeout)
603
+
604
+ conn.timeout = timeout_obj.connect_timeout
605
+
606
+ is_new_proxy_conn = self.proxy is not None and not getattr(conn, 'sock', None)
607
+ if is_new_proxy_conn:
608
+ self._prepare_proxy(conn)
609
+
610
+ # Make the request on the httplib connection object.
611
+ httplib_response = self._make_request(conn, method, url,
612
+ timeout=timeout_obj,
613
+ body=body, headers=headers,
614
+ chunked=chunked)
615
+
616
+ # If we're going to release the connection in ``finally:``, then
617
+ # the response doesn't need to know about the connection. Otherwise
618
+ # it will also try to release it and we'll have a double-release
619
+ # mess.
620
+ response_conn = conn if not release_conn else None
621
+
622
+ # Pass method to Response for length checking
623
+ response_kw['request_method'] = method
624
+
625
+ # Import httplib's response into our own wrapper object
626
+ response = self.ResponseCls.from_httplib(httplib_response,
627
+ pool=self,
628
+ connection=response_conn,
629
+ retries=retries,
630
+ **response_kw)
631
+
632
+ # Everything went great!
633
+ clean_exit = True
634
+
635
+ except queue.Empty:
636
+ # Timed out by queue.
637
+ raise EmptyPoolError(self, "No pool connections are available.")
638
+
639
+ except (TimeoutError, HTTPException, SocketError, ProtocolError,
640
+ BaseSSLError, SSLError, CertificateError) as e:
641
+ # Discard the connection for these exceptions. It will be
642
+ # replaced during the next _get_conn() call.
643
+ clean_exit = False
644
+ if isinstance(e, (BaseSSLError, CertificateError)):
645
+ e = SSLError(e)
646
+ elif isinstance(e, (SocketError, NewConnectionError)) and self.proxy:
647
+ e = ProxyError('Cannot connect to proxy.', e)
648
+ elif isinstance(e, (SocketError, HTTPException)):
649
+ e = ProtocolError('Connection aborted.', e)
650
+
651
+ retries = retries.increment(method, url, error=e, _pool=self,
652
+ _stacktrace=sys.exc_info()[2])
653
+ retries.sleep()
654
+
655
+ # Keep track of the error for the retry warning.
656
+ err = e
657
+
658
+ finally:
659
+ if not clean_exit:
660
+ # We hit some kind of exception, handled or otherwise. We need
661
+ # to throw the connection away unless explicitly told not to.
662
+ # Close the connection, set the variable to None, and make sure
663
+ # we put the None back in the pool to avoid leaking it.
664
+ conn = conn and conn.close()
665
+ release_this_conn = True
666
+
667
+ if release_this_conn:
668
+ # Put the connection back to be reused. If the connection is
669
+ # expired then it will be None, which will get replaced with a
670
+ # fresh connection during _get_conn.
671
+ self._put_conn(conn)
672
+
673
+ if not conn:
674
+ # Try again
675
+ log.warning("Retrying (%r) after connection "
676
+ "broken by '%r': %s", retries, err, url)
677
+ return self.urlopen(method, url, body, headers, retries,
678
+ redirect, assert_same_host,
679
+ timeout=timeout, pool_timeout=pool_timeout,
680
+ release_conn=release_conn, body_pos=body_pos,
681
+ **response_kw)
682
+
683
+ def drain_and_release_conn(response):
684
+ try:
685
+ # discard any remaining response body, the connection will be
686
+ # released back to the pool once the entire response is read
687
+ response.read()
688
+ except (TimeoutError, HTTPException, SocketError, ProtocolError,
689
+ BaseSSLError, SSLError):
690
+ pass
691
+
692
+ # Handle redirect?
693
+ redirect_location = redirect and response.get_redirect_location()
694
+ if redirect_location:
695
+ if response.status == 303:
696
+ method = 'GET'
697
+
698
+ try:
699
+ retries = retries.increment(method, url, response=response, _pool=self)
700
+ except MaxRetryError:
701
+ if retries.raise_on_redirect:
702
+ # Drain and release the connection for this response, since
703
+ # we're not returning it to be released manually.
704
+ drain_and_release_conn(response)
705
+ raise
706
+ return response
707
+
708
+ # drain and return the connection to the pool before recursing
709
+ drain_and_release_conn(response)
710
+
711
+ retries.sleep_for_retry(response)
712
+ log.debug("Redirecting %s -> %s", url, redirect_location)
713
+ return self.urlopen(
714
+ method, redirect_location, body, headers,
715
+ retries=retries, redirect=redirect,
716
+ assert_same_host=assert_same_host,
717
+ timeout=timeout, pool_timeout=pool_timeout,
718
+ release_conn=release_conn, body_pos=body_pos,
719
+ **response_kw)
720
+
721
+ # Check if we should retry the HTTP response.
722
+ has_retry_after = bool(response.getheader('Retry-After'))
723
+ if retries.is_retry(method, response.status, has_retry_after):
724
+ try:
725
+ retries = retries.increment(method, url, response=response, _pool=self)
726
+ except MaxRetryError:
727
+ if retries.raise_on_status:
728
+ # Drain and release the connection for this response, since
729
+ # we're not returning it to be released manually.
730
+ drain_and_release_conn(response)
731
+ raise
732
+ return response
733
+
734
+ # drain and return the connection to the pool before recursing
735
+ drain_and_release_conn(response)
736
+
737
+ retries.sleep(response)
738
+ log.debug("Retry: %s", url)
739
+ return self.urlopen(
740
+ method, url, body, headers,
741
+ retries=retries, redirect=redirect,
742
+ assert_same_host=assert_same_host,
743
+ timeout=timeout, pool_timeout=pool_timeout,
744
+ release_conn=release_conn,
745
+ body_pos=body_pos, **response_kw)
746
+
747
+ return response
748
+
749
+
750
+ class HTTPSConnectionPool(HTTPConnectionPool):
751
+ """
752
+ Same as :class:`.HTTPConnectionPool`, but HTTPS.
753
+
754
+ When Python is compiled with the :mod:`ssl` module, then
755
+ :class:`.VerifiedHTTPSConnection` is used, which *can* verify certificates,
756
+ instead of :class:`.HTTPSConnection`.
757
+
758
+ :class:`.VerifiedHTTPSConnection` uses one of ``assert_fingerprint``,
759
+ ``assert_hostname`` and ``host`` in this order to verify connections.
760
+ If ``assert_hostname`` is False, no verification is done.
761
+
762
+ The ``key_file``, ``cert_file``, ``cert_reqs``, ``ca_certs``,
763
+ ``ca_cert_dir``, and ``ssl_version`` are only used if :mod:`ssl` is
764
+ available and are fed into :meth:`urllib3.util.ssl_wrap_socket` to upgrade
765
+ the connection socket into an SSL socket.
766
+ """
767
+
768
+ scheme = 'https'
769
+ ConnectionCls = HTTPSConnection
770
+
771
+ def __init__(self, host, port=None,
772
+ strict=False, timeout=Timeout.DEFAULT_TIMEOUT, maxsize=1,
773
+ block=False, headers=None, retries=None,
774
+ _proxy=None, _proxy_headers=None,
775
+ key_file=None, cert_file=None, cert_reqs=None,
776
+ ca_certs=None, ssl_version=None,
777
+ assert_hostname=None, assert_fingerprint=None,
778
+ ca_cert_dir=None, **conn_kw):
779
+
780
+ HTTPConnectionPool.__init__(self, host, port, strict, timeout, maxsize,
781
+ block, headers, retries, _proxy, _proxy_headers,
782
+ **conn_kw)
783
+
784
+ if ca_certs and cert_reqs is None:
785
+ cert_reqs = 'CERT_REQUIRED'
786
+
787
+ self.key_file = key_file
788
+ self.cert_file = cert_file
789
+ self.cert_reqs = cert_reqs
790
+ self.ca_certs = ca_certs
791
+ self.ca_cert_dir = ca_cert_dir
792
+ self.ssl_version = ssl_version
793
+ self.assert_hostname = assert_hostname
794
+ self.assert_fingerprint = assert_fingerprint
795
+
796
+ def _prepare_conn(self, conn):
797
+ """
798
+ Prepare the ``connection`` for :meth:`urllib3.util.ssl_wrap_socket`
799
+ and establish the tunnel if proxy is used.
800
+ """
801
+
802
+ if isinstance(conn, VerifiedHTTPSConnection):
803
+ conn.set_cert(key_file=self.key_file,
804
+ cert_file=self.cert_file,
805
+ cert_reqs=self.cert_reqs,
806
+ ca_certs=self.ca_certs,
807
+ ca_cert_dir=self.ca_cert_dir,
808
+ assert_hostname=self.assert_hostname,
809
+ assert_fingerprint=self.assert_fingerprint)
810
+ conn.ssl_version = self.ssl_version
811
+ return conn
812
+
813
+ def _prepare_proxy(self, conn):
814
+ """
815
+ Establish tunnel connection early, because otherwise httplib
816
+ would improperly set Host: header to proxy's IP:port.
817
+ """
818
+ conn.set_tunnel(self._proxy_host, self.port, self.proxy_headers)
819
+ conn.connect()
820
+
821
+ def _new_conn(self):
822
+ """
823
+ Return a fresh :class:`httplib.HTTPSConnection`.
824
+ """
825
+ self.num_connections += 1
826
+ log.debug("Starting new HTTPS connection (%d): %s:%s",
827
+ self.num_connections, self.host, self.port or "443")
828
+
829
+ if not self.ConnectionCls or self.ConnectionCls is DummyConnection:
830
+ raise SSLError("Can't connect to HTTPS URL because the SSL "
831
+ "module is not available.")
832
+
833
+ actual_host = self.host
834
+ actual_port = self.port
835
+ if self.proxy is not None:
836
+ actual_host = self.proxy.host
837
+ actual_port = self.proxy.port
838
+
839
+ conn = self.ConnectionCls(host=actual_host, port=actual_port,
840
+ timeout=self.timeout.connect_timeout,
841
+ strict=self.strict, **self.conn_kw)
842
+
843
+ return self._prepare_conn(conn)
844
+
845
+ def _validate_conn(self, conn):
846
+ """
847
+ Called right before a request is made, after the socket is created.
848
+ """
849
+ super(HTTPSConnectionPool, self)._validate_conn(conn)
850
+
851
+ # Force connect early to allow us to validate the connection.
852
+ if not getattr(conn, 'sock', None): # AppEngine might not have `.sock`
853
+ conn.connect()
854
+
855
+ if not conn.is_verified:
856
+ warnings.warn((
857
+ 'Unverified HTTPS request is being made. '
858
+ 'Adding certificate verification is strongly advised. See: '
859
+ 'https://urllib3.readthedocs.io/en/latest/advanced-usage.html'
860
+ '#ssl-warnings'),
861
+ InsecureRequestWarning)
862
+
863
+
864
+ def connection_from_url(url, **kw):
865
+ """
866
+ Given a url, return an :class:`.ConnectionPool` instance of its host.
867
+
868
+ This is a shortcut for not having to parse out the scheme, host, and port
869
+ of the url before creating an :class:`.ConnectionPool` instance.
870
+
871
+ :param url:
872
+ Absolute URL string that must include the scheme. Port is optional.
873
+
874
+ :param \\**kw:
875
+ Passes additional parameters to the constructor of the appropriate
876
+ :class:`.ConnectionPool`. Useful for specifying things like
877
+ timeout, maxsize, headers, etc.
878
+
879
+ Example::
880
+
881
+ >>> conn = connection_from_url('http://google.com/')
882
+ >>> r = conn.request('GET', '/')
883
+ """
884
+ scheme, host, port = get_host(url)
885
+ port = port or port_by_scheme.get(scheme, 80)
886
+ if scheme == 'https':
887
+ return HTTPSConnectionPool(host, port=port, **kw)
888
+ else:
889
+ return HTTPConnectionPool(host, port=port, **kw)
890
+
891
+
892
+ def _ipv6_host(host, scheme):
893
+ """
894
+ Process IPv6 address literals
895
+ """
896
+
897
+ # httplib doesn't like it when we include brackets in IPv6 addresses
898
+ # Specifically, if we include brackets but also pass the port then
899
+ # httplib crazily doubles up the square brackets on the Host header.
900
+ # Instead, we need to make sure we never pass ``None`` as the port.
901
+ # However, for backward compatibility reasons we can't actually
902
+ # *assert* that. See http://bugs.python.org/issue28539
903
+ #
904
+ # Also if an IPv6 address literal has a zone identifier, the
905
+ # percent sign might be URIencoded, convert it back into ASCII
906
+ if host.startswith('[') and host.endswith(']'):
907
+ host = host.replace('%25', '%').strip('[]')
908
+ if scheme in NORMALIZABLE_SCHEMES:
909
+ host = host.lower()
910
+ return host