httpclient.py 26 KB

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