### Navigation
- [index](# "General Index")
- [modules](# "Python Module Index") |
- [next](# "tornado.httputil — Manipulate HTTP headers and URLs") |
- [previous](# "tornado.httpserver — Non-blocking HTTP server") |
- [Tornado 4.4.dev1 documentation](#) »
- [HTTP servers and clients](#) »
# `tornado.httpclient` — Asynchronous HTTP client
Blocking and non-blocking HTTP client interfaces.
This module defines a common interface shared by two implementations,`simple_httpclient` and `curl_httpclient`. Applications may eitherinstantiate their chosen implementation class directly or use the[`AsyncHTTPClient`](# "tornado.httpclient.AsyncHTTPClient") class from this module, which selects an implementationthat can be overridden with the [`AsyncHTTPClient.configure`](# "tornado.httpclient.AsyncHTTPClient.configure") method.
The default implementation is `simple_httpclient`, and this is expectedto be suitable for most users' needs. However, some applications may wishto switch to `curl_httpclient` for reasons such as the following:
- `curl_httpclient` has some features not found in `simple_httpclient`,including support for HTTP proxies and the ability to use a specifiednetwork interface.
- `curl_httpclient` is more likely to be compatible with sites that arenot-quite-compliant with the HTTP spec, or sites that use little-exercisedfeatures of HTTP.
- `curl_httpclient` is faster.
- `curl_httpclient` was the default prior to Tornado 2.0.
Note that if you are using `curl_httpclient`, it is highlyrecommended that you use a recent version of `libcurl` and`pycurl`. Currently the minimum supported version of libcurl is7.21.1, and the minimum version of pycurl is 7.18.2. It is highlyrecommended that your `libcurl` installation is built withasynchronous DNS resolver (threaded or c-ares), otherwise you mayencounter various problems with request timeouts (for moreinformation, see[http://curl.haxx.se/libcurl/c/curl_easy_setopt.html#CURLOPTCONNECTTIMEOUTMS](http://curl.haxx.se/libcurl/c/curl_easy_setopt.html#CURLOPTCONNECTTIMEOUTMS)and comments in curl_httpclient.py).
To select `curl_httpclient`, call [`AsyncHTTPClient.configure`](# "tornado.httpclient.AsyncHTTPClient.configure") at startup:
~~~
AsyncHTTPClient.configure("tornado.curl_httpclient.CurlAsyncHTTPClient")
~~~
### HTTP client interfaces
*class *`tornado.httpclient.``HTTPClient`(*async_client_class=None*, ***kwargs*)[[source]](#)
A blocking HTTP client.
This interface is provided for convenience and testing; most applicationsthat are running an IOLoop will want to use [`AsyncHTTPClient`](# "tornado.httpclient.AsyncHTTPClient") instead.Typical usage looks like this:
~~~
http_client = httpclient.HTTPClient()
try:
response = http_client.fetch("http://www.google.com/")
print response.body
except httpclient.HTTPError as e:
# HTTPError is raised for non-200 responses; the response
# can be found in e.response.
print("Error: " + str(e))
except Exception as e:
# Other errors are possible, such as IOError.
print("Error: " + str(e))
http_client.close()
~~~
`close`()[[source]](#)
Closes the HTTPClient, freeing any resources used.
`fetch`(*request*, ***kwargs*)[[source]](#)
Executes a request, returning an [`HTTPResponse`](# "tornado.httpclient.HTTPResponse").
The request may be either a string URL or an [`HTTPRequest`](# "tornado.httpclient.HTTPRequest") object.If it is a string, we construct an [`HTTPRequest`](# "tornado.httpclient.HTTPRequest") using any additionalkwargs: `HTTPRequest(request, **kwargs)`
If an error occurs during the fetch, we raise an [`HTTPError`](# "tornado.httpclient.HTTPError") unlessthe `raise_error` keyword argument is set to False.
*class *`tornado.httpclient.``AsyncHTTPClient`[[source]](#)
An non-blocking HTTP client.
Example usage:
~~~
def handle_request(response):
if response.error:
print "Error:", response.error
else:
print response.body
http_client = AsyncHTTPClient()
http_client.fetch("http://www.google.com/", handle_request)
~~~
The constructor for this class is magic in several respects: Itactually creates an instance of an implementation-specificsubclass, and instances are reused as a kind of pseudo-singleton(one per [`IOLoop`](# "tornado.ioloop.IOLoop")). The keyword argument `force_instance=True`can be used to suppress this singleton behavior. Unless`force_instance=True` is used, no arguments other than`io_loop` should be passed to the [`AsyncHTTPClient`](# "tornado.httpclient.AsyncHTTPClient") constructor.The implementation subclass as well as arguments to itsconstructor can be set with the static method [`configure()`](# "tornado.httpclient.AsyncHTTPClient.configure")
All [`AsyncHTTPClient`](# "tornado.httpclient.AsyncHTTPClient") implementations support a `defaults`keyword argument, which can be used to set default values for[`HTTPRequest`](# "tornado.httpclient.HTTPRequest") attributes. For example:
~~~
AsyncHTTPClient.configure(
None, defaults=dict(user_agent="MyUserAgent"))
# or with force_instance:
client = AsyncHTTPClient(force_instance=True,
defaults=dict(user_agent="MyUserAgent"))
~~~
Changed in version 4.1: The `io_loop` argument is deprecated.
`close`()[[source]](#)
Destroys this HTTP client, freeing any file descriptors used.
This method is **not needed in normal use** due to the waythat [`AsyncHTTPClient`](# "tornado.httpclient.AsyncHTTPClient") objects are transparently reused.`close()` is generally only necessary when either the[`IOLoop`](# "tornado.ioloop.IOLoop") is also being closed, or the `force_instance=True`argument was used when creating the [`AsyncHTTPClient`](# "tornado.httpclient.AsyncHTTPClient").
No other methods may be called on the [`AsyncHTTPClient`](# "tornado.httpclient.AsyncHTTPClient") after`close()`.
`fetch`(*request*, *callback=None*, *raise_error=True*, ***kwargs*)[[source]](#)
Executes a request, asynchronously returning an [`HTTPResponse`](# "tornado.httpclient.HTTPResponse").
The request may be either a string URL or an [`HTTPRequest`](# "tornado.httpclient.HTTPRequest") object.If it is a string, we construct an [`HTTPRequest`](# "tornado.httpclient.HTTPRequest") using any additionalkwargs: `HTTPRequest(request, **kwargs)`
This method returns a [`Future`](# "tornado.concurrent.Future") whose result is an[`HTTPResponse`](# "tornado.httpclient.HTTPResponse"). By default, the `Future` will raise an[`HTTPError`](# "tornado.httpclient.HTTPError") if the request returned a non-200 response code(other errors may also be raised if the server could not becontacted). Instead, if `raise_error` is set to False, theresponse will always be returned regardless of the responsecode.
If a `callback` is given, it will be invoked with the [`HTTPResponse`](# "tornado.httpclient.HTTPResponse").In the callback interface, [`HTTPError`](# "tornado.httpclient.HTTPError") is not automatically raised.Instead, you must check the response's `error` attribute orcall its [`rethrow`](# "tornado.httpclient.HTTPResponse.rethrow") method.
*classmethod *`configure`(*impl*, ***kwargs*)[[source]](#)
Configures the [`AsyncHTTPClient`](# "tornado.httpclient.AsyncHTTPClient") subclass to use.
`AsyncHTTPClient()` actually creates an instance of a subclass.This method may be called with either a class object or thefully-qualified name of such a class (or `None` to use the default,`SimpleAsyncHTTPClient`)
If additional keyword arguments are given, they will be passedto the constructor of each subclass instance created. Thekeyword argument `max_clients` determines the maximum numberof simultaneous [`fetch()`](# "tornado.httpclient.AsyncHTTPClient.fetch") operations that canexecute in parallel on each [`IOLoop`](# "tornado.ioloop.IOLoop"). Additional argumentsmay be supported depending on the implementation class in use.
Example:
~~~
AsyncHTTPClient.configure("tornado.curl_httpclient.CurlAsyncHTTPClient")
~~~
### Request objects
*class *`tornado.httpclient.``HTTPRequest`(*url*, *method='GET'*, *headers=None*, *body=None*, *auth_username=None*, *auth_password=None*, *auth_mode=None*, *connect_timeout=None*, *request_timeout=None*, *if_modified_since=None*, *follow_redirects=None*, *max_redirects=None*, *user_agent=None*, *use_gzip=None*, *network_interface=None*, *streaming_callback=None*, *header_callback=None*, *prepare_curl_callback=None*, *proxy_host=None*, *proxy_port=None*, *proxy_username=None*, *proxy_password=None*, *allow_nonstandard_methods=None*, *validate_cert=None*, *ca_certs=None*, *allow_ipv6=None*, *client_key=None*, *client_cert=None*, *body_producer=None*, *expect_100_continue=False*, *decompress_response=None*, *ssl_options=None*)[[source]](#)
HTTP client request object.
All parameters except `url` are optional.
<table class="docutils field-list" frame="void" rules="none"><col class="field-name"/><col class="field-body"/><tbody valign="top"><tr class="field-odd field"><th class="field-name">Parameters:</th><td class="field-body"><ul class="first last simple"><li><strong>url</strong> (<a class="reference external" href="https://docs.python.org/3.4/library/string.html#module-string" title="(in Python v3.4)"><em>string</em></a><span class="link-target"> [https://docs.python.org/3.4/library/string.html#module-string]</span>) – URL to fetch</li><li><strong>method</strong> (<a class="reference external" href="https://docs.python.org/3.4/library/string.html#module-string" title="(in Python v3.4)"><em>string</em></a><span class="link-target"> [https://docs.python.org/3.4/library/string.html#module-string]</span>) – HTTP method, e.g. “GET” or “POST”</li><li><strong>headers</strong> (<a class="reference internal" href="httputil.html#tornado.httputil.HTTPHeaders" title="tornado.httputil.HTTPHeaders"><code class="xref py py-obj docutils literal"><span class="pre">HTTPHeaders</span></code></a> or <a class="reference external" href="https://docs.python.org/3.4/library/stdtypes.html#dict" title="(in Python v3.4)"><code class="xref py py-obj docutils literal"><span class="pre">dict</span></code></a><span class="link-target"> [https://docs.python.org/3.4/library/stdtypes.html#dict]</span>) – Additional HTTP headers to pass on the request</li><li><strong>body</strong> – HTTP request body as a string (byte or unicode; if unicodethe utf-8 encoding will be used)</li><li><strong>body_producer</strong> – Callable used for lazy/asynchronous request bodies.It is called with one argument, a <code class="docutils literal"><span class="pre">write</span></code> function, and shouldreturn a <a class="reference internal" href="concurrent.html#tornado.concurrent.Future" title="tornado.concurrent.Future"><code class="xref py py-obj docutils literal"><span class="pre">Future</span></code></a>. It should call the write function with newdata as it becomes available. The write function returns a<a class="reference internal" href="concurrent.html#tornado.concurrent.Future" title="tornado.concurrent.Future"><code class="xref py py-obj docutils literal"><span class="pre">Future</span></code></a> which can be used for flow control.Only one of <code class="docutils literal"><span class="pre">body</span></code> and <code class="docutils literal"><span class="pre">body_producer</span></code> maybe specified. <code class="docutils literal"><span class="pre">body_producer</span></code> is not supported on<code class="docutils literal"><span class="pre">curl_httpclient</span></code>. When using <code class="docutils literal"><span class="pre">body_producer</span></code> it is recommendedto pass a <code class="docutils literal"><span class="pre">Content-Length</span></code> in the headers as otherwise chunkedencoding will be used, and many servers do not support chunkedencoding on requests. New in Tornado 4.0</li><li><strong>auth_username</strong> (<a class="reference external" href="https://docs.python.org/3.4/library/string.html#module-string" title="(in Python v3.4)"><em>string</em></a><span class="link-target"> [https://docs.python.org/3.4/library/string.html#module-string]</span>) – Username for HTTP authentication</li><li><strong>auth_password</strong> (<a class="reference external" href="https://docs.python.org/3.4/library/string.html#module-string" title="(in Python v3.4)"><em>string</em></a><span class="link-target"> [https://docs.python.org/3.4/library/string.html#module-string]</span>) – Password for HTTP authentication</li><li><strong>auth_mode</strong> (<a class="reference external" href="https://docs.python.org/3.4/library/string.html#module-string" title="(in Python v3.4)"><em>string</em></a><span class="link-target"> [https://docs.python.org/3.4/library/string.html#module-string]</span>) – Authentication mode; default is “basic”.Allowed values are implementation-defined; <code class="docutils literal"><span class="pre">curl_httpclient</span></code>supports “basic” and “digest”; <code class="docutils literal"><span class="pre">simple_httpclient</span></code> only supports“basic”</li><li><strong>connect_timeout</strong> (<a class="reference external" href="https://docs.python.org/3.4/library/functions.html#float" title="(in Python v3.4)"><em>float</em></a><span class="link-target"> [https://docs.python.org/3.4/library/functions.html#float]</span>) – Timeout for initial connection in seconds</li><li><strong>request_timeout</strong> (<a class="reference external" href="https://docs.python.org/3.4/library/functions.html#float" title="(in Python v3.4)"><em>float</em></a><span class="link-target"> [https://docs.python.org/3.4/library/functions.html#float]</span>) – Timeout for entire request in seconds</li><li><strong>if_modified_since</strong> (<a class="reference external" href="https://docs.python.org/3.4/library/datetime.html#module-datetime" title="(in Python v3.4)"><code class="xref py py-obj docutils literal"><span class="pre">datetime</span></code></a><span class="link-target"> [https://docs.python.org/3.4/library/datetime.html#module-datetime]</span> or <a class="reference external" href="https://docs.python.org/3.4/library/functions.html#float" title="(in Python v3.4)"><code class="xref py py-obj docutils literal"><span class="pre">float</span></code></a><span class="link-target"> [https://docs.python.org/3.4/library/functions.html#float]</span>) – Timestamp for <code class="docutils literal"><span class="pre">If-Modified-Since</span></code> header</li><li><strong>follow_redirects</strong> (<a class="reference external" href="https://docs.python.org/3.4/library/functions.html#bool" title="(in Python v3.4)"><em>bool</em></a><span class="link-target"> [https://docs.python.org/3.4/library/functions.html#bool]</span>) – Should redirects be followed automaticallyor return the 3xx response?</li><li><strong>max_redirects</strong> (<a class="reference external" href="https://docs.python.org/3.4/library/functions.html#int" title="(in Python v3.4)"><em>int</em></a><span class="link-target"> [https://docs.python.org/3.4/library/functions.html#int]</span>) – Limit for <code class="docutils literal"><span class="pre">follow_redirects</span></code></li><li><strong>user_agent</strong> (<a class="reference external" href="https://docs.python.org/3.4/library/string.html#module-string" title="(in Python v3.4)"><em>string</em></a><span class="link-target"> [https://docs.python.org/3.4/library/string.html#module-string]</span>) – String to send as <code class="docutils literal"><span class="pre">User-Agent</span></code> header</li><li><strong>decompress_response</strong> (<a class="reference external" href="https://docs.python.org/3.4/library/functions.html#bool" title="(in Python v3.4)"><em>bool</em></a><span class="link-target"> [https://docs.python.org/3.4/library/functions.html#bool]</span>) – Request a compressed response fromthe server and decompress it after downloading. Default is True.New in Tornado 4.0.</li><li><strong>use_gzip</strong> (<a class="reference external" href="https://docs.python.org/3.4/library/functions.html#bool" title="(in Python v3.4)"><em>bool</em></a><span class="link-target"> [https://docs.python.org/3.4/library/functions.html#bool]</span>) – Deprecated alias for <code class="docutils literal"><span class="pre">decompress_response</span></code>since Tornado 4.0.</li><li><strong>network_interface</strong> (<a class="reference external" href="https://docs.python.org/3.4/library/string.html#module-string" title="(in Python v3.4)"><em>string</em></a><span class="link-target"> [https://docs.python.org/3.4/library/string.html#module-string]</span>) – Network interface to use for request.<code class="docutils literal"><span class="pre">curl_httpclient</span></code> only; see note below.</li><li><strong>streaming_callback</strong> (<a class="reference external" href="https://docs.python.org/3.4/library/functions.html#callable" title="(in Python v3.4)"><em>callable</em></a><span class="link-target"> [https://docs.python.org/3.4/library/functions.html#callable]</span>) – If set, <code class="docutils literal"><span class="pre">streaming_callback</span></code> willbe run with each chunk of data as it is received, and<code class="docutils literal"><span class="pre">HTTPResponse.body</span></code> and <code class="docutils literal"><span class="pre">HTTPResponse.buffer</span></code> will be empty inthe final response.</li><li><strong>header_callback</strong> (<a class="reference external" href="https://docs.python.org/3.4/library/functions.html#callable" title="(in Python v3.4)"><em>callable</em></a><span class="link-target"> [https://docs.python.org/3.4/library/functions.html#callable]</span>) – If set, <code class="docutils literal"><span class="pre">header_callback</span></code> willbe run with each header line as it is received (including thefirst line, e.g. <code class="docutils literal"><span class="pre">HTTP/1.0</span> <span class="pre">200</span> <span class="pre">OK\r\n</span></code>, and a final linecontaining only <code class="docutils literal"><span class="pre">\r\n</span></code>. All lines include the trailing newlinecharacters). <code class="docutils literal"><span class="pre">HTTPResponse.headers</span></code> will be empty in the finalresponse. This is most useful in conjunction with<code class="docutils literal"><span class="pre">streaming_callback</span></code>, because it's the only way to get access toheader data while the request is in progress.</li><li><strong>prepare_curl_callback</strong> (<a class="reference external" href="https://docs.python.org/3.4/library/functions.html#callable" title="(in Python v3.4)"><em>callable</em></a><span class="link-target"> [https://docs.python.org/3.4/library/functions.html#callable]</span>) – If set, will be called witha <code class="docutils literal"><span class="pre">pycurl.Curl</span></code> object to allow the application to make additional<code class="docutils literal"><span class="pre">setopt</span></code> calls.</li><li><strong>proxy_host</strong> (<a class="reference external" href="https://docs.python.org/3.4/library/string.html#module-string" title="(in Python v3.4)"><em>string</em></a><span class="link-target"> [https://docs.python.org/3.4/library/string.html#module-string]</span>) – HTTP proxy hostname. To use proxies,<code class="docutils literal"><span class="pre">proxy_host</span></code> and <code class="docutils literal"><span class="pre">proxy_port</span></code> must be set; <code class="docutils literal"><span class="pre">proxy_username</span></code> and<code class="docutils literal"><span class="pre">proxy_pass</span></code> are optional. Proxies are currently only supportedwith <code class="docutils literal"><span class="pre">curl_httpclient</span></code>.</li><li><strong>proxy_port</strong> (<a class="reference external" href="https://docs.python.org/3.4/library/functions.html#int" title="(in Python v3.4)"><em>int</em></a><span class="link-target"> [https://docs.python.org/3.4/library/functions.html#int]</span>) – HTTP proxy port</li><li><strong>proxy_username</strong> (<a class="reference external" href="https://docs.python.org/3.4/library/string.html#module-string" title="(in Python v3.4)"><em>string</em></a><span class="link-target"> [https://docs.python.org/3.4/library/string.html#module-string]</span>) – HTTP proxy username</li><li><strong>proxy_password</strong> (<a class="reference external" href="https://docs.python.org/3.4/library/string.html#module-string" title="(in Python v3.4)"><em>string</em></a><span class="link-target"> [https://docs.python.org/3.4/library/string.html#module-string]</span>) – HTTP proxy password</li><li><strong>allow_nonstandard_methods</strong> (<a class="reference external" href="https://docs.python.org/3.4/library/functions.html#bool" title="(in Python v3.4)"><em>bool</em></a><span class="link-target"> [https://docs.python.org/3.4/library/functions.html#bool]</span>) – Allow unknown values for <code class="docutils literal"><span class="pre">method</span></code>argument?</li><li><strong>validate_cert</strong> (<a class="reference external" href="https://docs.python.org/3.4/library/functions.html#bool" title="(in Python v3.4)"><em>bool</em></a><span class="link-target"> [https://docs.python.org/3.4/library/functions.html#bool]</span>) – For HTTPS requests, validate the server'scertificate?</li><li><strong>ca_certs</strong> (<a class="reference external" href="https://docs.python.org/3.4/library/string.html#module-string" title="(in Python v3.4)"><em>string</em></a><span class="link-target"> [https://docs.python.org/3.4/library/string.html#module-string]</span>) – filename of CA certificates in PEM format,or None to use defaults. See note below when used with<code class="docutils literal"><span class="pre">curl_httpclient</span></code>.</li><li><strong>client_key</strong> (<a class="reference external" href="https://docs.python.org/3.4/library/string.html#module-string" title="(in Python v3.4)"><em>string</em></a><span class="link-target"> [https://docs.python.org/3.4/library/string.html#module-string]</span>) – Filename for client SSL key, if any. Seenote below when used with <code class="docutils literal"><span class="pre">curl_httpclient</span></code>.</li><li><strong>client_cert</strong> (<a class="reference external" href="https://docs.python.org/3.4/library/string.html#module-string" title="(in Python v3.4)"><em>string</em></a><span class="link-target"> [https://docs.python.org/3.4/library/string.html#module-string]</span>) – Filename for client SSL certificate, if any.See note below when used with <code class="docutils literal"><span class="pre">curl_httpclient</span></code>.</li><li><strong>ssl_options</strong> (<a class="reference external" href="https://docs.python.org/3.4/library/ssl.html#ssl.SSLContext" title="(in Python v3.4)"><em>ssl.SSLContext</em></a><span class="link-target"> [https://docs.python.org/3.4/library/ssl.html#ssl.SSLContext]</span>) – <a class="reference external" href="https://docs.python.org/3.4/library/ssl.html#ssl.SSLContext" title="(in Python v3.4)"><code class="xref py py-obj docutils literal"><span class="pre">ssl.SSLContext</span></code></a><span class="link-target"> [https://docs.python.org/3.4/library/ssl.html#ssl.SSLContext]</span> object for use in<code class="docutils literal"><span class="pre">simple_httpclient</span></code> (unsupported by <code class="docutils literal"><span class="pre">curl_httpclient</span></code>).Overrides <code class="docutils literal"><span class="pre">validate_cert</span></code>, <code class="docutils literal"><span class="pre">ca_certs</span></code>, <code class="docutils literal"><span class="pre">client_key</span></code>,and <code class="docutils literal"><span class="pre">client_cert</span></code>.</li><li><strong>allow_ipv6</strong> (<a class="reference external" href="https://docs.python.org/3.4/library/functions.html#bool" title="(in Python v3.4)"><em>bool</em></a><span class="link-target"> [https://docs.python.org/3.4/library/functions.html#bool]</span>) – Use IPv6 when available? Default is true.</li><li><strong>expect_100_continue</strong> (<a class="reference external" href="https://docs.python.org/3.4/library/functions.html#bool" title="(in Python v3.4)"><em>bool</em></a><span class="link-target"> [https://docs.python.org/3.4/library/functions.html#bool]</span>) – If true, send the<code class="docutils literal"><span class="pre">Expect:</span> <span class="pre">100-continue</span></code> header and wait for a continue responsebefore sending the request body. Only supported withsimple_httpclient.</li></ul></td></tr></tbody></table>
Note
When using `curl_httpclient` certain options may beinherited by subsequent fetches because `pycurl` doesnot allow them to be cleanly reset. This applies to the`ca_certs`, `client_key`, `client_cert`, and`network_interface` arguments. If you use theseoptions, you should pass them on every request (you don'thave to always use the same values, but it's not possibleto mix requests that specify these options with ones thatuse the defaults).
New in version 3.1: The `auth_mode` argument.
New in version 4.0: The `body_producer` and `expect_100_continue` arguments.
New in version 4.2: The `ssl_options` argument.
### Response objects
*class *`tornado.httpclient.``HTTPResponse`(*request*, *code*, *headers=None*, *buffer=None*, *effective_url=None*, *error=None*, *request_time=None*, *time_info=None*, *reason=None*)[[source]](#)
HTTP Response object.
Attributes:
- request: HTTPRequest object
- code: numeric HTTP status code, e.g. 200 or 404
- reason: human-readable reason phrase describing the status code
- headers: [`tornado.httputil.HTTPHeaders`](# "tornado.httputil.HTTPHeaders") object
- effective_url: final location of the resource after following anyredirects
- buffer: `cStringIO` object for response body
- body: response body as string (created on demand from `self.buffer`)
- error: Exception object, if any
- request_time: seconds from request start to finish
- time_info: dictionary of diagnostic timing information from the request.Available data are subject to change, but currently uses timingsavailable from [http://curl.haxx.se/libcurl/c/curl_easy_getinfo.html](http://curl.haxx.se/libcurl/c/curl_easy_getinfo.html),plus `queue`, which is the delay (if any) introduced by waiting fora slot under [`AsyncHTTPClient`](# "tornado.httpclient.AsyncHTTPClient")‘s `max_clients` setting.
`rethrow`()[[source]](#)
If there was an error on the request, raise an [`HTTPError`](# "tornado.httpclient.HTTPError").
### Exceptions
*exception *`tornado.httpclient.``HTTPError`(*code*, *message=None*, *response=None*)[[source]](#)
Exception thrown for an unsuccessful HTTP request.
Attributes:
- `code` - HTTP error integer error code, e.g. 404. Error code 599 isused when no HTTP response was received, e.g. for a timeout.
- `response` - [`HTTPResponse`](# "tornado.httpclient.HTTPResponse") object, if any.
Note that if `follow_redirects` is False, redirects become HTTPErrors,and you can look at `error.response.headers['Location']` to see thedestination of the redirect.
### Command-line interface
This module provides a simple command-line interface to fetch a urlusing Tornado's HTTP client. Example usage:
~~~
# Fetch the url and print its body
python -m tornado.httpclient http://www.google.com
# Just print the headers
python -m tornado.httpclient --print_headers --print_body=false http://www.google.com
~~~
### Implementations
*class *`tornado.simple_httpclient.``SimpleAsyncHTTPClient`[[source]](#)
Non-blocking HTTP client with no external dependencies.
This class implements an HTTP 1.1 client on top of Tornado's IOStreams.Some features found in the curl-based AsyncHTTPClient are not yetsupported. In particular, proxies are not supported, connectionsare not reused, and callers cannot select the network interface to beused.
`initialize`(*io_loop*, *max_clients=10*, *hostname_mapping=None*, *max_buffer_size=104857600*, *resolver=None*, *defaults=None*, *max_header_size=None*, *max_body_size=None*)[[source]](#)
Creates a AsyncHTTPClient.
Only a single AsyncHTTPClient instance exists per IOLoopin order to provide limitations on the number of pending connections.`force_instance=True` may be used to suppress this behavior.
Note that because of this implicit reuse, unless `force_instance`is used, only the first call to the constructor actually usesits arguments. It is recommended to use the `configure` methodinstead of the constructor to ensure that arguments take effect.
`max_clients` is the number of concurrent requests that can bein progress; when this limit is reached additional requests will bequeued. Note that time spent waiting in this queue still countsagainst the `request_timeout`.
`hostname_mapping` is a dictionary mapping hostnames to IP addresses.It can be used to make local DNS changes when modifying system-widesettings like `/etc/hosts` is not possible or desirable (e.g. inunittests).
`max_buffer_size` (default 100MB) is the number of bytesthat can be read into memory at once. `max_body_size`(defaults to `max_buffer_size`) is the largest response bodythat the client will accept. Without a`streaming_callback`, the smaller of these two limitsapplies; with a `streaming_callback` only `max_body_size`does.
Changed in version 4.2: Added the `max_body_size` argument.
*class *`tornado.curl_httpclient.``CurlAsyncHTTPClient`(*io_loop*, *max_clients=10*, *defaults=None*)
`libcurl`-based HTTP client.
© Copyright 2009-2016, The Tornado Authors. Created using [Sphinx](http://sphinx-doc.org/) 1.3.5.
- User's guide
- Introduction
- Asynchronous and non-Blocking I/O
- Coroutines
- Queue example - a concurrent web spider
- Structure of a Tornado web application
- Templates and UI
- Authentication and security
- Running and deploying
- Web framework
- tornado.web — RequestHandler and Application classes
- tornado.template — Flexible output generation
- tornado.escape — Escaping and string manipulation
- tornado.locale — Internationalization support
- tornado.websocket — Bidirectional communication to the browser
- HTTP servers and clients
- tornado.httpserver — Non-blocking HTTP server
- tornado.httpclient — Asynchronous HTTP client
- tornado.httputil — Manipulate HTTP headers and URLs
- tornado.http1connection – HTTP/1.x client/server implementation
- Asynchronous networking
- tornado.ioloop — Main event loop
- tornado.iostream — Convenient wrappers for non-blocking sockets
- tornado.netutil — Miscellaneous network utilities
- tornado.tcpclient — IOStream connection factory
- tornado.tcpserver — Basic IOStream-based TCP server
- Coroutines and concurrency
- tornado.gen — Simplify asynchronous code
- tornado.concurrent — Work with threads and futures
- tornado.locks – Synchronization primitives
- tornado.queues – Queues for coroutines
- tornado.process — Utilities for multiple processes
- Integration with other services
- tornado.auth — Third-party login with OpenID and OAuth
- tornado.wsgi — Interoperability with other Python frameworks and servers
- tornado.platform.asyncio — Bridge between asyncio and Tornado
- tornado.platform.caresresolver — Asynchronous DNS Resolver using C-Ares
- tornado.platform.twisted — Bridges between Twisted and Tornado
- Utilities
- tornado.autoreload — Automatically detect code changes in development
- tornado.log — Logging support
- tornado.options — Command-line parsing
- tornado.stack_context — Exception handling across asynchronous callbacks
- tornado.testing — Unit testing support for asynchronous code
- tornado.util — General-purpose utilities
- Frequently Asked Questions
- Release notes
- What's new in Tornado 4.3
- What's new in Tornado 4.2.1
- What's new in Tornado 4.2
- What's new in Tornado 4.1
- What's new in Tornado 4.0.2
- What's new in Tornado 4.0.1
- What's new in Tornado 4.0
- What's new in Tornado 3.2.2
- What's new in Tornado 3.2.1
- What's new in Tornado 3.2
- What's new in Tornado 3.1.1
- What's new in Tornado 3.1
- What's new in Tornado 3.0.2
- What's new in Tornado 3.0.1
- What's new in Tornado 3.0
- What's new in Tornado 2.4.1
- What's new in Tornado 2.4
- What's new in Tornado 2.3
- What's new in Tornado 2.2.1
- What's new in Tornado 2.2
- What's new in Tornado 2.1.1
- What's new in Tornado 2.1
- What's new in Tornado 2.0
- What's new in Tornado 1.2.1
- What's new in Tornado 1.2
- What's new in Tornado 1.1.1
- What's new in Tornado 1.1
- What's new in Tornado 1.0.1
- What's new in Tornado 1.0