httpclient.py 31 KB

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