httpclient.py 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790
  1. """Blocking and non-blocking HTTP client interfaces.
  2. This module defines a common interface shared by two implementations,
  3. ``simple_httpclient`` and ``curl_httpclient``. Applications may either
  4. instantiate their chosen implementation class directly or use the
  5. `AsyncHTTPClient` class from this module, which selects an implementation
  6. that can be overridden with the `AsyncHTTPClient.configure` method.
  7. The default implementation is ``simple_httpclient``, and this is expected
  8. to be suitable for most users' needs. However, some applications may wish
  9. to switch to ``curl_httpclient`` for reasons such as the following:
  10. * ``curl_httpclient`` has some features not found in ``simple_httpclient``,
  11. including support for HTTP proxies and the ability to use a specified
  12. network interface.
  13. * ``curl_httpclient`` is more likely to be compatible with sites that are
  14. not-quite-compliant with the HTTP spec, or sites that use little-exercised
  15. features of HTTP.
  16. * ``curl_httpclient`` is faster.
  17. Note that if you are using ``curl_httpclient``, it is highly
  18. recommended that you use a recent version of ``libcurl`` and
  19. ``pycurl``. Currently the minimum supported version of libcurl is
  20. 7.22.0, and the minimum version of pycurl is 7.18.2. It is highly
  21. recommended that your ``libcurl`` installation is built with
  22. asynchronous DNS resolver (threaded or c-ares), otherwise you may
  23. encounter various problems with request timeouts (for more
  24. information, see
  25. http://curl.haxx.se/libcurl/c/curl_easy_setopt.html#CURLOPTCONNECTTIMEOUTMS
  26. and comments in curl_httpclient.py).
  27. To select ``curl_httpclient``, call `AsyncHTTPClient.configure` at startup::
  28. AsyncHTTPClient.configure("tornado.curl_httpclient.CurlAsyncHTTPClient")
  29. """
  30. import datetime
  31. import functools
  32. from io import BytesIO
  33. import ssl
  34. import time
  35. import weakref
  36. from tornado.concurrent import (
  37. Future,
  38. future_set_result_unless_cancelled,
  39. future_set_exception_unless_cancelled,
  40. )
  41. from tornado.escape import utf8, native_str
  42. from tornado import gen, httputil
  43. from tornado.ioloop import IOLoop
  44. from tornado.util import Configurable
  45. from typing import Type, Any, Union, Dict, Callable, Optional, cast
  46. class HTTPClient:
  47. """A blocking HTTP client.
  48. This interface is provided to make it easier to share code between
  49. synchronous and asynchronous applications. Applications that are
  50. running an `.IOLoop` must use `AsyncHTTPClient` instead.
  51. Typical usage looks like this::
  52. http_client = httpclient.HTTPClient()
  53. try:
  54. response = http_client.fetch("http://www.google.com/")
  55. print(response.body)
  56. except httpclient.HTTPError as e:
  57. # HTTPError is raised for non-200 responses; the response
  58. # can be found in e.response.
  59. print("Error: " + str(e))
  60. except Exception as e:
  61. # Other errors are possible, such as IOError.
  62. print("Error: " + str(e))
  63. http_client.close()
  64. .. versionchanged:: 5.0
  65. Due to limitations in `asyncio`, it is no longer possible to
  66. use the synchronous ``HTTPClient`` while an `.IOLoop` is running.
  67. Use `AsyncHTTPClient` instead.
  68. """
  69. def __init__(
  70. self,
  71. async_client_class: "Optional[Type[AsyncHTTPClient]]" = None,
  72. **kwargs: Any,
  73. ) -> None:
  74. # Initialize self._closed at the beginning of the constructor
  75. # so that an exception raised here doesn't lead to confusing
  76. # failures in __del__.
  77. self._closed = True
  78. self._io_loop = IOLoop(make_current=False)
  79. if async_client_class is None:
  80. async_client_class = AsyncHTTPClient
  81. # Create the client while our IOLoop is "current", without
  82. # clobbering the thread's real current IOLoop (if any).
  83. async def make_client() -> "AsyncHTTPClient":
  84. await gen.sleep(0)
  85. assert async_client_class is not None
  86. return async_client_class(**kwargs)
  87. self._async_client = self._io_loop.run_sync(make_client)
  88. self._closed = False
  89. def __del__(self) -> None:
  90. self.close()
  91. def close(self) -> None:
  92. """Closes the HTTPClient, freeing any resources used."""
  93. if not self._closed:
  94. self._async_client.close()
  95. self._io_loop.close()
  96. self._closed = True
  97. def fetch(
  98. self, request: Union["HTTPRequest", str], **kwargs: Any
  99. ) -> "HTTPResponse":
  100. """Executes a request, returning an `HTTPResponse`.
  101. The request may be either a string URL or an `HTTPRequest` object.
  102. If it is a string, we construct an `HTTPRequest` using any additional
  103. kwargs: ``HTTPRequest(request, **kwargs)``
  104. If an error occurs during the fetch, we raise an `HTTPError` unless
  105. the ``raise_error`` keyword argument is set to False.
  106. """
  107. response = self._io_loop.run_sync(
  108. functools.partial(self._async_client.fetch, request, **kwargs)
  109. )
  110. return response
  111. class AsyncHTTPClient(Configurable):
  112. """An non-blocking HTTP client.
  113. Example usage::
  114. async def f():
  115. http_client = AsyncHTTPClient()
  116. try:
  117. response = await http_client.fetch("http://www.google.com")
  118. except Exception as e:
  119. print("Error: %s" % e)
  120. else:
  121. print(response.body)
  122. The constructor for this class is magic in several respects: It
  123. actually creates an instance of an implementation-specific
  124. subclass, and instances are reused as a kind of pseudo-singleton
  125. (one per `.IOLoop`). The keyword argument ``force_instance=True``
  126. can be used to suppress this singleton behavior. Unless
  127. ``force_instance=True`` is used, no arguments should be passed to
  128. the `AsyncHTTPClient` constructor. The implementation subclass as
  129. well as arguments to its constructor can be set with the static
  130. method `configure()`
  131. All `AsyncHTTPClient` implementations support a ``defaults``
  132. keyword argument, which can be used to set default values for
  133. `HTTPRequest` attributes. For example::
  134. AsyncHTTPClient.configure(
  135. None, defaults=dict(user_agent="MyUserAgent"))
  136. # or with force_instance:
  137. client = AsyncHTTPClient(force_instance=True,
  138. defaults=dict(user_agent="MyUserAgent"))
  139. .. versionchanged:: 5.0
  140. The ``io_loop`` argument (deprecated since version 4.1) has been removed.
  141. """
  142. _instance_cache = None # type: Dict[IOLoop, AsyncHTTPClient]
  143. @classmethod
  144. def configurable_base(cls) -> Type[Configurable]:
  145. return AsyncHTTPClient
  146. @classmethod
  147. def configurable_default(cls) -> Type[Configurable]:
  148. from tornado.simple_httpclient import SimpleAsyncHTTPClient
  149. return SimpleAsyncHTTPClient
  150. @classmethod
  151. def _async_clients(cls) -> Dict[IOLoop, "AsyncHTTPClient"]:
  152. attr_name = "_async_client_dict_" + cls.__name__
  153. if not hasattr(cls, attr_name):
  154. setattr(cls, attr_name, weakref.WeakKeyDictionary())
  155. return getattr(cls, attr_name)
  156. def __new__(cls, force_instance: bool = False, **kwargs: Any) -> "AsyncHTTPClient":
  157. io_loop = IOLoop.current()
  158. if force_instance:
  159. instance_cache = None
  160. else:
  161. instance_cache = cls._async_clients()
  162. if instance_cache is not None and io_loop in instance_cache:
  163. return instance_cache[io_loop]
  164. instance = super().__new__(cls, **kwargs) # type: ignore
  165. # Make sure the instance knows which cache to remove itself from.
  166. # It can't simply call _async_clients() because we may be in
  167. # __new__(AsyncHTTPClient) but instance.__class__ may be
  168. # SimpleAsyncHTTPClient.
  169. instance._instance_cache = instance_cache
  170. if instance_cache is not None:
  171. instance_cache[instance.io_loop] = instance
  172. return instance
  173. def initialize(self, defaults: Optional[Dict[str, Any]] = None) -> None:
  174. self.io_loop = IOLoop.current()
  175. self.defaults = dict(HTTPRequest._DEFAULTS)
  176. if defaults is not None:
  177. self.defaults.update(defaults)
  178. self._closed = False
  179. def close(self) -> None:
  180. """Destroys this HTTP client, freeing any file descriptors used.
  181. This method is **not needed in normal use** due to the way
  182. that `AsyncHTTPClient` objects are transparently reused.
  183. ``close()`` is generally only necessary when either the
  184. `.IOLoop` is also being closed, or the ``force_instance=True``
  185. argument was used when creating the `AsyncHTTPClient`.
  186. No other methods may be called on the `AsyncHTTPClient` after
  187. ``close()``.
  188. """
  189. if self._closed:
  190. return
  191. self._closed = True
  192. if self._instance_cache is not None:
  193. cached_val = self._instance_cache.pop(self.io_loop, None)
  194. # If there's an object other than self in the instance
  195. # cache for our IOLoop, something has gotten mixed up. A
  196. # value of None appears to be possible when this is called
  197. # from a destructor (HTTPClient.__del__) as the weakref
  198. # gets cleared before the destructor runs.
  199. if cached_val is not None and cached_val is not self:
  200. raise RuntimeError("inconsistent AsyncHTTPClient cache")
  201. def fetch(
  202. self,
  203. request: Union[str, "HTTPRequest"],
  204. raise_error: bool = True,
  205. **kwargs: Any,
  206. ) -> "Future[HTTPResponse]":
  207. """Executes a request, asynchronously returning an `HTTPResponse`.
  208. The request may be either a string URL or an `HTTPRequest` object.
  209. If it is a string, we construct an `HTTPRequest` using any additional
  210. kwargs: ``HTTPRequest(request, **kwargs)``
  211. This method returns a `.Future` whose result is an
  212. `HTTPResponse`. By default, the ``Future`` will raise an
  213. `HTTPError` if the request returned a non-200 response code
  214. (other errors may also be raised if the server could not be
  215. contacted). Instead, if ``raise_error`` is set to False, the
  216. response will always be returned regardless of the response
  217. code.
  218. If a ``callback`` is given, it will be invoked with the `HTTPResponse`.
  219. In the callback interface, `HTTPError` is not automatically raised.
  220. Instead, you must check the response's ``error`` attribute or
  221. call its `~HTTPResponse.rethrow` method.
  222. .. versionchanged:: 6.0
  223. The ``callback`` argument was removed. Use the returned
  224. `.Future` instead.
  225. The ``raise_error=False`` argument only affects the
  226. `HTTPError` raised when a non-200 response code is used,
  227. instead of suppressing all errors.
  228. """
  229. if self._closed:
  230. raise RuntimeError("fetch() called on closed AsyncHTTPClient")
  231. if not isinstance(request, HTTPRequest):
  232. request = HTTPRequest(url=request, **kwargs)
  233. else:
  234. if kwargs:
  235. raise ValueError(
  236. "kwargs can't be used if request is an HTTPRequest object"
  237. )
  238. # We may modify this (to add Host, Accept-Encoding, etc),
  239. # so make sure we don't modify the caller's object. This is also
  240. # where normal dicts get converted to HTTPHeaders objects.
  241. request.headers = httputil.HTTPHeaders(request.headers)
  242. request_proxy = _RequestProxy(request, self.defaults)
  243. future = Future() # type: Future[HTTPResponse]
  244. def handle_response(response: "HTTPResponse") -> None:
  245. if response.error:
  246. if raise_error or not response._error_is_response_code:
  247. future_set_exception_unless_cancelled(future, response.error)
  248. return
  249. future_set_result_unless_cancelled(future, response)
  250. self.fetch_impl(cast(HTTPRequest, request_proxy), handle_response)
  251. return future
  252. def fetch_impl(
  253. self, request: "HTTPRequest", callback: Callable[["HTTPResponse"], None]
  254. ) -> None:
  255. raise NotImplementedError()
  256. @classmethod
  257. def configure(
  258. cls, impl: "Union[None, str, Type[Configurable]]", **kwargs: Any
  259. ) -> None:
  260. """Configures the `AsyncHTTPClient` subclass to use.
  261. ``AsyncHTTPClient()`` actually creates an instance of a subclass.
  262. This method may be called with either a class object or the
  263. fully-qualified name of such a class (or ``None`` to use the default,
  264. ``SimpleAsyncHTTPClient``)
  265. If additional keyword arguments are given, they will be passed
  266. to the constructor of each subclass instance created. The
  267. keyword argument ``max_clients`` determines the maximum number
  268. of simultaneous `~AsyncHTTPClient.fetch()` operations that can
  269. execute in parallel on each `.IOLoop`. Additional arguments
  270. may be supported depending on the implementation class in use.
  271. Example::
  272. AsyncHTTPClient.configure("tornado.curl_httpclient.CurlAsyncHTTPClient")
  273. """
  274. super().configure(impl, **kwargs)
  275. class HTTPRequest:
  276. """HTTP client request object."""
  277. _headers = None # type: Union[Dict[str, str], httputil.HTTPHeaders]
  278. # Default values for HTTPRequest parameters.
  279. # Merged with the values on the request object by AsyncHTTPClient
  280. # implementations.
  281. _DEFAULTS = dict(
  282. connect_timeout=20.0,
  283. request_timeout=20.0,
  284. follow_redirects=True,
  285. max_redirects=5,
  286. decompress_response=True,
  287. proxy_password="",
  288. allow_nonstandard_methods=False,
  289. validate_cert=True,
  290. )
  291. def __init__(
  292. self,
  293. url: str,
  294. method: str = "GET",
  295. headers: Optional[Union[Dict[str, str], httputil.HTTPHeaders]] = None,
  296. body: Optional[Union[bytes, str]] = None,
  297. auth_username: Optional[str] = None,
  298. auth_password: Optional[str] = None,
  299. auth_mode: Optional[str] = None,
  300. connect_timeout: Optional[float] = None,
  301. request_timeout: Optional[float] = None,
  302. if_modified_since: Optional[Union[float, datetime.datetime]] = None,
  303. follow_redirects: Optional[bool] = None,
  304. max_redirects: Optional[int] = None,
  305. user_agent: Optional[str] = None,
  306. use_gzip: Optional[bool] = None,
  307. network_interface: Optional[str] = None,
  308. streaming_callback: Optional[Callable[[bytes], None]] = None,
  309. header_callback: Optional[Callable[[str], None]] = None,
  310. prepare_curl_callback: Optional[Callable[[Any], None]] = None,
  311. proxy_host: Optional[str] = None,
  312. proxy_port: Optional[int] = None,
  313. proxy_username: Optional[str] = None,
  314. proxy_password: Optional[str] = None,
  315. proxy_auth_mode: Optional[str] = None,
  316. allow_nonstandard_methods: Optional[bool] = None,
  317. validate_cert: Optional[bool] = None,
  318. ca_certs: Optional[str] = None,
  319. allow_ipv6: Optional[bool] = None,
  320. client_key: Optional[str] = None,
  321. client_cert: Optional[str] = None,
  322. body_producer: Optional[
  323. Callable[[Callable[[bytes], None]], "Future[None]"]
  324. ] = None,
  325. expect_100_continue: bool = False,
  326. decompress_response: Optional[bool] = None,
  327. ssl_options: Optional[Union[Dict[str, Any], ssl.SSLContext]] = None,
  328. ) -> None:
  329. r"""All parameters except ``url`` are optional.
  330. :arg str url: URL to fetch
  331. :arg str method: HTTP method, e.g. "GET" or "POST"
  332. :arg headers: Additional HTTP headers to pass on the request
  333. :type headers: `~tornado.httputil.HTTPHeaders` or `dict`
  334. :arg body: HTTP request body as a string (byte or unicode; if unicode
  335. the utf-8 encoding will be used)
  336. :type body: `str` or `bytes`
  337. :arg collections.abc.Callable body_producer: Callable used for
  338. lazy/asynchronous request bodies.
  339. It is called with one argument, a ``write`` function, and should
  340. return a `.Future`. It should call the write function with new
  341. data as it becomes available. The write function returns a
  342. `.Future` which can be used for flow control.
  343. Only one of ``body`` and ``body_producer`` may
  344. be specified. ``body_producer`` is not supported on
  345. ``curl_httpclient``. When using ``body_producer`` it is recommended
  346. to pass a ``Content-Length`` in the headers as otherwise chunked
  347. encoding will be used, and many servers do not support chunked
  348. encoding on requests. New in Tornado 4.0
  349. :arg str auth_username: Username for HTTP authentication
  350. :arg str auth_password: Password for HTTP authentication
  351. :arg str auth_mode: Authentication mode; default is "basic".
  352. Allowed values are implementation-defined; ``curl_httpclient``
  353. supports "basic" and "digest"; ``simple_httpclient`` only supports
  354. "basic"
  355. :arg float connect_timeout: Timeout for initial connection in seconds,
  356. default 20 seconds (0 means no timeout)
  357. :arg float request_timeout: Timeout for entire request in seconds,
  358. default 20 seconds (0 means no timeout)
  359. :arg if_modified_since: Timestamp for ``If-Modified-Since`` header
  360. :type if_modified_since: `datetime` or `float`
  361. :arg bool follow_redirects: Should redirects be followed automatically
  362. or return the 3xx response? Default True.
  363. :arg int max_redirects: Limit for ``follow_redirects``, default 5.
  364. :arg str user_agent: String to send as ``User-Agent`` header
  365. :arg bool decompress_response: Request a compressed response from
  366. the server and decompress it after downloading. Default is True.
  367. New in Tornado 4.0.
  368. :arg bool use_gzip: Deprecated alias for ``decompress_response``
  369. since Tornado 4.0.
  370. :arg str network_interface: Network interface or source IP to use for request.
  371. See ``curl_httpclient`` note below.
  372. :arg collections.abc.Callable streaming_callback: If set, ``streaming_callback`` will
  373. be run with each chunk of data as it is received, and
  374. ``HTTPResponse.body`` and ``HTTPResponse.buffer`` will be empty in
  375. the final response.
  376. :arg collections.abc.Callable header_callback: If set, ``header_callback`` will
  377. be run with each header line as it is received (including the
  378. first line, e.g. ``HTTP/1.0 200 OK\r\n``, and a final line
  379. containing only ``\r\n``. All lines include the trailing newline
  380. characters). ``HTTPResponse.headers`` will be empty in the final
  381. response. This is most useful in conjunction with
  382. ``streaming_callback``, because it's the only way to get access to
  383. header data while the request is in progress.
  384. :arg collections.abc.Callable prepare_curl_callback: If set, will be called with
  385. a ``pycurl.Curl`` object to allow the application to make additional
  386. ``setopt`` calls.
  387. :arg str proxy_host: HTTP proxy hostname. To use proxies,
  388. ``proxy_host`` and ``proxy_port`` must be set; ``proxy_username``,
  389. ``proxy_pass`` and ``proxy_auth_mode`` are optional. Proxies are
  390. currently only supported with ``curl_httpclient``.
  391. :arg int proxy_port: HTTP proxy port
  392. :arg str proxy_username: HTTP proxy username
  393. :arg str proxy_password: HTTP proxy password
  394. :arg str proxy_auth_mode: HTTP proxy Authentication mode;
  395. default is "basic". supports "basic" and "digest"
  396. :arg bool allow_nonstandard_methods: Allow unknown values for ``method``
  397. argument? Default is False.
  398. :arg bool validate_cert: For HTTPS requests, validate the server's
  399. certificate? Default is True.
  400. :arg str ca_certs: filename of CA certificates in PEM format,
  401. or None to use defaults. See note below when used with
  402. ``curl_httpclient``.
  403. :arg str client_key: Filename for client SSL key, if any. See
  404. note below when used with ``curl_httpclient``.
  405. :arg str client_cert: Filename for client SSL certificate, if any.
  406. See note below when used with ``curl_httpclient``.
  407. :arg ssl.SSLContext ssl_options: `ssl.SSLContext` object for use in
  408. ``simple_httpclient`` (unsupported by ``curl_httpclient``).
  409. Overrides ``validate_cert``, ``ca_certs``, ``client_key``,
  410. and ``client_cert``.
  411. :arg bool allow_ipv6: Use IPv6 when available? Default is True.
  412. :arg bool expect_100_continue: If true, send the
  413. ``Expect: 100-continue`` header and wait for a continue response
  414. before sending the request body. Only supported with
  415. ``simple_httpclient``.
  416. .. note::
  417. When using ``curl_httpclient`` certain options may be
  418. inherited by subsequent fetches because ``pycurl`` does
  419. not allow them to be cleanly reset. This applies to the
  420. ``ca_certs``, ``client_key``, ``client_cert``, and
  421. ``network_interface`` arguments. If you use these
  422. options, you should pass them on every request (you don't
  423. have to always use the same values, but it's not possible
  424. to mix requests that specify these options with ones that
  425. use the defaults).
  426. .. versionadded:: 3.1
  427. The ``auth_mode`` argument.
  428. .. versionadded:: 4.0
  429. The ``body_producer`` and ``expect_100_continue`` arguments.
  430. .. versionadded:: 4.2
  431. The ``ssl_options`` argument.
  432. .. versionadded:: 4.5
  433. The ``proxy_auth_mode`` argument.
  434. """
  435. # Note that some of these attributes go through property setters
  436. # defined below.
  437. self.headers = headers # type: ignore
  438. if if_modified_since:
  439. self.headers["If-Modified-Since"] = httputil.format_timestamp(
  440. if_modified_since
  441. )
  442. self.proxy_host = proxy_host
  443. self.proxy_port = proxy_port
  444. self.proxy_username = proxy_username
  445. self.proxy_password = proxy_password
  446. self.proxy_auth_mode = proxy_auth_mode
  447. self.url = url
  448. self.method = method
  449. self.body = body # type: ignore
  450. self.body_producer = body_producer
  451. self.auth_username = auth_username
  452. self.auth_password = auth_password
  453. self.auth_mode = auth_mode
  454. self.connect_timeout = connect_timeout
  455. self.request_timeout = request_timeout
  456. self.follow_redirects = follow_redirects
  457. self.max_redirects = max_redirects
  458. self.user_agent = user_agent
  459. if decompress_response is not None:
  460. self.decompress_response = decompress_response # type: Optional[bool]
  461. else:
  462. self.decompress_response = use_gzip
  463. self.network_interface = network_interface
  464. self.streaming_callback = streaming_callback
  465. self.header_callback = header_callback
  466. self.prepare_curl_callback = prepare_curl_callback
  467. self.allow_nonstandard_methods = allow_nonstandard_methods
  468. self.validate_cert = validate_cert
  469. self.ca_certs = ca_certs
  470. self.allow_ipv6 = allow_ipv6
  471. self.client_key = client_key
  472. self.client_cert = client_cert
  473. self.ssl_options = ssl_options
  474. self.expect_100_continue = expect_100_continue
  475. self.start_time = time.time()
  476. @property
  477. def headers(self) -> httputil.HTTPHeaders:
  478. # TODO: headers may actually be a plain dict until fairly late in
  479. # the process (AsyncHTTPClient.fetch), but practically speaking,
  480. # whenever the property is used they're already HTTPHeaders.
  481. return self._headers # type: ignore
  482. @headers.setter
  483. def headers(self, value: Union[Dict[str, str], httputil.HTTPHeaders]) -> None:
  484. if value is None:
  485. self._headers = httputil.HTTPHeaders()
  486. else:
  487. self._headers = value # type: ignore
  488. @property
  489. def body(self) -> bytes:
  490. return self._body
  491. @body.setter
  492. def body(self, value: Union[bytes, str]) -> None:
  493. self._body = utf8(value)
  494. class HTTPResponse:
  495. """HTTP Response object.
  496. Attributes:
  497. * ``request``: HTTPRequest object
  498. * ``code``: numeric HTTP status code, e.g. 200 or 404
  499. * ``reason``: human-readable reason phrase describing the status code
  500. * ``headers``: `tornado.httputil.HTTPHeaders` object
  501. * ``effective_url``: final location of the resource after following any
  502. redirects
  503. * ``buffer``: ``cStringIO`` object for response body
  504. * ``body``: response body as bytes (created on demand from ``self.buffer``)
  505. * ``error``: Exception object, if any
  506. * ``request_time``: seconds from request start to finish. Includes all
  507. network operations from DNS resolution to receiving the last byte of
  508. data. Does not include time spent in the queue (due to the
  509. ``max_clients`` option). If redirects were followed, only includes
  510. the final request.
  511. * ``start_time``: Time at which the HTTP operation started, based on
  512. `time.time` (not the monotonic clock used by `.IOLoop.time`). May
  513. be ``None`` if the request timed out while in the queue.
  514. * ``time_info``: dictionary of diagnostic timing information from the
  515. request. Available data are subject to change, but currently uses timings
  516. available from http://curl.haxx.se/libcurl/c/curl_easy_getinfo.html,
  517. plus ``queue``, which is the delay (if any) introduced by waiting for
  518. a slot under `AsyncHTTPClient`'s ``max_clients`` setting.
  519. .. versionadded:: 5.1
  520. Added the ``start_time`` attribute.
  521. .. versionchanged:: 5.1
  522. The ``request_time`` attribute previously included time spent in the queue
  523. for ``simple_httpclient``, but not in ``curl_httpclient``. Now queueing time
  524. is excluded in both implementations. ``request_time`` is now more accurate for
  525. ``curl_httpclient`` because it uses a monotonic clock when available.
  526. """
  527. # I'm not sure why these don't get type-inferred from the references in __init__.
  528. error = None # type: Optional[BaseException]
  529. _error_is_response_code = False
  530. request = None # type: HTTPRequest
  531. def __init__(
  532. self,
  533. request: HTTPRequest,
  534. code: int,
  535. headers: Optional[httputil.HTTPHeaders] = None,
  536. buffer: Optional[BytesIO] = None,
  537. effective_url: Optional[str] = None,
  538. error: Optional[BaseException] = None,
  539. request_time: Optional[float] = None,
  540. time_info: Optional[Dict[str, float]] = None,
  541. reason: Optional[str] = None,
  542. start_time: Optional[float] = None,
  543. ) -> None:
  544. if isinstance(request, _RequestProxy):
  545. self.request = request.request
  546. else:
  547. self.request = request
  548. self.code = code
  549. self.reason = reason or httputil.responses.get(code, "Unknown")
  550. if headers is not None:
  551. self.headers = headers
  552. else:
  553. self.headers = httputil.HTTPHeaders()
  554. self.buffer = buffer
  555. self._body = None # type: Optional[bytes]
  556. if effective_url is None:
  557. self.effective_url = request.url
  558. else:
  559. self.effective_url = effective_url
  560. self._error_is_response_code = False
  561. if error is None:
  562. if self.code < 200 or self.code >= 300:
  563. self._error_is_response_code = True
  564. self.error = HTTPError(self.code, message=self.reason, response=self)
  565. else:
  566. self.error = None
  567. else:
  568. self.error = error
  569. self.start_time = start_time
  570. self.request_time = request_time
  571. self.time_info = time_info or {}
  572. @property
  573. def body(self) -> bytes:
  574. if self.buffer is None:
  575. return b""
  576. elif self._body is None:
  577. self._body = self.buffer.getvalue()
  578. return self._body
  579. def rethrow(self) -> None:
  580. """If there was an error on the request, raise an `HTTPError`."""
  581. if self.error:
  582. raise self.error
  583. def __repr__(self) -> str:
  584. args = ",".join("%s=%r" % i for i in sorted(self.__dict__.items()))
  585. return f"{self.__class__.__name__}({args})"
  586. class HTTPClientError(Exception):
  587. """Exception thrown for an unsuccessful HTTP request.
  588. Attributes:
  589. * ``code`` - HTTP error integer error code, e.g. 404. Error code 599 is
  590. used when no HTTP response was received, e.g. for a timeout.
  591. * ``response`` - `HTTPResponse` object, if any.
  592. Note that if ``follow_redirects`` is False, redirects become HTTPErrors,
  593. and you can look at ``error.response.headers['Location']`` to see the
  594. destination of the redirect.
  595. .. versionchanged:: 5.1
  596. Renamed from ``HTTPError`` to ``HTTPClientError`` to avoid collisions with
  597. `tornado.web.HTTPError`. The name ``tornado.httpclient.HTTPError`` remains
  598. as an alias.
  599. """
  600. def __init__(
  601. self,
  602. code: int,
  603. message: Optional[str] = None,
  604. response: Optional[HTTPResponse] = None,
  605. ) -> None:
  606. self.code = code
  607. self.message = message or httputil.responses.get(code, "Unknown")
  608. self.response = response
  609. super().__init__(code, message, response)
  610. def __str__(self) -> str:
  611. return "HTTP %d: %s" % (self.code, self.message)
  612. # There is a cyclic reference between self and self.response,
  613. # which breaks the default __repr__ implementation.
  614. # (especially on pypy, which doesn't have the same recursion
  615. # detection as cpython).
  616. __repr__ = __str__
  617. HTTPError = HTTPClientError
  618. class _RequestProxy:
  619. """Combines an object with a dictionary of defaults.
  620. Used internally by AsyncHTTPClient implementations.
  621. """
  622. def __init__(
  623. self, request: HTTPRequest, defaults: Optional[Dict[str, Any]]
  624. ) -> None:
  625. self.request = request
  626. self.defaults = defaults
  627. def __getattr__(self, name: str) -> Any:
  628. request_attr = getattr(self.request, name)
  629. if request_attr is not None:
  630. return request_attr
  631. elif self.defaults is not None:
  632. return self.defaults.get(name, None)
  633. else:
  634. return None
  635. def main() -> None:
  636. from tornado.options import define, options, parse_command_line
  637. define("print_headers", type=bool, default=False)
  638. define("print_body", type=bool, default=True)
  639. define("follow_redirects", type=bool, default=True)
  640. define("validate_cert", type=bool, default=True)
  641. define("proxy_host", type=str)
  642. define("proxy_port", type=int)
  643. args = parse_command_line()
  644. client = HTTPClient()
  645. for arg in args:
  646. try:
  647. response = client.fetch(
  648. arg,
  649. follow_redirects=options.follow_redirects,
  650. validate_cert=options.validate_cert,
  651. proxy_host=options.proxy_host,
  652. proxy_port=options.proxy_port,
  653. )
  654. except HTTPError as e:
  655. if e.response is not None:
  656. response = e.response
  657. else:
  658. raise
  659. if options.print_headers:
  660. print(response.headers)
  661. if options.print_body:
  662. print(native_str(response.body))
  663. client.close()
  664. if __name__ == "__main__":
  665. main()