httpclient.py 30 KB

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