### Navigation
- [index](# "General Index")
- [modules](# "Python Module Index") |
- [next](# "tornado.http1connection – HTTP/1.x client/server implementation") |
- [previous](# "tornado.httpclient — Asynchronous HTTP client") |
- [Tornado 4.4.dev1 documentation](#) »
- [HTTP servers and clients](#) »
# `tornado.httputil` — Manipulate HTTP headers and URLs
HTTP utility code shared by clients and servers.
This module also defines the [`HTTPServerRequest`](# "tornado.httputil.HTTPServerRequest") class which is exposedvia [`tornado.web.RequestHandler.request`](# "tornado.web.RequestHandler.request").
*class *`tornado.httputil.``HTTPHeaders`(**args*, ***kwargs*)[[source]](#)
A dictionary that maintains `Http-Header-Case` for all keys.
Supports multiple values per key via a pair of new methods,[`add()`](# "tornado.httputil.HTTPHeaders.add") and [`get_list()`](# "tornado.httputil.HTTPHeaders.get_list"). The regular dictionary interfacereturns a single value per key, with multiple values joined by acomma.
~~~
>>> h = HTTPHeaders({"content-type": "text/html"})
>>> list(h.keys())
['Content-Type']
>>> h["Content-Type"]
'text/html'
~~~
~~~
>>> h.add("Set-Cookie", "A=B")
>>> h.add("Set-Cookie", "C=D")
>>> h["set-cookie"]
'A=B,C=D'
>>> h.get_list("set-cookie")
['A=B', 'C=D']
~~~
~~~
>>> for (k,v) in sorted(h.get_all()):
... print('%s: %s' % (k,v))
...
Content-Type: text/html
Set-Cookie: A=B
Set-Cookie: C=D
~~~
`add`(*name*, *value*)[[source]](#)
Adds a new value for the given key.
`get_list`(*name*)[[source]](#)
Returns all values for the given header as a list.
`get_all`()[[source]](#)
Returns an iterable of all (name, value) pairs.
If a header has multiple values, multiple pairs will bereturned with the same name.
`parse_line`(*line*)[[source]](#)
Updates the dictionary with a single header line.
~~~
>>> h = HTTPHeaders()
>>> h.parse_line("Content-Type: text/html")
>>> h.get('content-type')
'text/html'
~~~
*classmethod *`parse`(*headers*)[[source]](#)
Returns a dictionary from HTTP header text.
~~~
>>> h = HTTPHeaders.parse("Content-Type: text/html\r\nContent-Length: 42\r\n")
>>> sorted(h.items())
[('Content-Length', '42'), ('Content-Type', 'text/html')]
~~~
*class *`tornado.httputil.``HTTPServerRequest`(*method=None*, *uri=None*, *version='HTTP/1.0'*, *headers=None*, *body=None*, *host=None*, *files=None*, *connection=None*, *start_line=None*)[[source]](#)
A single HTTP request.
All attributes are type [`str`](https://docs.python.org/3.4/library/stdtypes.html#str "(in Python v3.4)") [https://docs.python.org/3.4/library/stdtypes.html#str] unless otherwise noted.
`method`
HTTP request method, e.g. “GET” or “POST”
`uri`
The requested uri.
`path`
The path portion of [`uri`](# "tornado.httputil.HTTPServerRequest.uri")
`query`
The query portion of [`uri`](# "tornado.httputil.HTTPServerRequest.uri")
`version`
HTTP version specified in request, e.g. “HTTP/1.1”
`headers`
[`HTTPHeaders`](# "tornado.httputil.HTTPHeaders") dictionary-like object for request headers. Acts likea case-insensitive dictionary with additional methods for repeatedheaders.
`body`
Request body, if present, as a byte string.
`remote_ip`
Client's IP address as a string. If `HTTPServer.xheaders` is set,will pass along the real IP address provided by a load balancerin the `X-Real-Ip` or `X-Forwarded-For` header.
Changed in version 3.1: The list format of `X-Forwarded-For` is now supported.
`protocol`
The protocol used, either “http” or “https”. If `HTTPServer.xheaders`is set, will pass along the protocol used by a load balancer ifreported via an `X-Scheme` header.
`host`
The requested hostname, usually taken from the `Host` header.
`arguments`
GET/POST arguments are available in the arguments property, whichmaps arguments names to lists of values (to support multiple valuesfor individual names). Names are of type [`str`](https://docs.python.org/3.4/library/stdtypes.html#str "(in Python v3.4)") [https://docs.python.org/3.4/library/stdtypes.html#str], while argumentsare byte strings. Note that this is different from[`RequestHandler.get_argument`](# "tornado.web.RequestHandler.get_argument"), which returns argument values asunicode strings.
`query_arguments`
Same format as `arguments`, but contains only arguments extractedfrom the query string.
New in version 3.2.
`body_arguments`
Same format as `arguments`, but contains only arguments extractedfrom the request body.
New in version 3.2.
`files`
File uploads are available in the files property, which maps filenames to lists of [`HTTPFile`](# "tornado.httputil.HTTPFile").
`connection`
An HTTP request is attached to a single HTTP connection, which canbe accessed through the “connection” attribute. Since connectionsare typically kept open in HTTP/1.1, multiple requests can be handledsequentially on a single connection.
Changed in version 4.0: Moved from `tornado.httpserver.HTTPRequest`.
`supports_http_1_1`()[[source]](#)
Returns True if this request supports HTTP/1.1 semantics.
Deprecated since version 4.0: Applications are less likely to need this information with theintroduction of [`HTTPConnection`](# "tornado.httputil.HTTPConnection"). If you still need it, accessthe `version` attribute directly.
`cookies`
A dictionary of Cookie.Morsel objects.
`write`(*chunk*, *callback=None*)[[source]](#)
Writes the given chunk to the response stream.
Deprecated since version 4.0: Use `request.connection` and the [`HTTPConnection`](# "tornado.httputil.HTTPConnection") methodsto write the response.
`finish`()[[source]](#)
Finishes this HTTP request on the open connection.
Deprecated since version 4.0: Use `request.connection` and the [`HTTPConnection`](# "tornado.httputil.HTTPConnection") methodsto write the response.
`full_url`()[[source]](#)
Reconstructs the full URL for this request.
`request_time`()[[source]](#)
Returns the amount of time it took for this request to execute.
`get_ssl_certificate`(*binary_form=False*)[[source]](#)
Returns the client's SSL certificate, if any.
To use client certificates, the HTTPServer's[`ssl.SSLContext.verify_mode`](https://docs.python.org/3.4/library/ssl.html#ssl.SSLContext.verify_mode "(in Python v3.4)") [https://docs.python.org/3.4/library/ssl.html#ssl.SSLContext.verify_mode] field must be set, e.g.:
~~~
ssl_ctx = ssl.create_default_context(ssl.Purpose.CLIENT_AUTH)
ssl_ctx.load_cert_chain("foo.crt", "foo.key")
ssl_ctx.load_verify_locations("cacerts.pem")
ssl_ctx.verify_mode = ssl.CERT_REQUIRED
server = HTTPServer(app, ssl_options=ssl_ctx)
~~~
By default, the return value is a dictionary (or None, if noclient certificate is present). If `binary_form` is true, aDER-encoded form of the certificate is returned instead. SeeSSLSocket.getpeercert() in the standard library for moredetails.[http://docs.python.org/library/ssl.html#sslsocket-objects](http://docs.python.org/library/ssl.html#sslsocket-objects)
*exception *`tornado.httputil.``HTTPInputError`[[source]](#)
Exception class for malformed HTTP requests or responsesfrom remote sources.
New in version 4.0.
*exception *`tornado.httputil.``HTTPOutputError`[[source]](#)
Exception class for errors in HTTP output.
New in version 4.0.
*class *`tornado.httputil.``HTTPServerConnectionDelegate`[[source]](#)
Implement this interface to handle requests from [`HTTPServer`](# "tornado.httpserver.HTTPServer").
New in version 4.0.
`start_request`(*server_conn*, *request_conn*)[[source]](#)
This method is called by the server when a new request has started.
<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>server_conn</strong> – is an opaque object representing the long-lived(e.g. tcp-level) connection.</li><li><strong>request_conn</strong> – is a <a class="reference internal" href="#tornado.httputil.HTTPConnection" title="tornado.httputil.HTTPConnection"><code class="xref py py-obj docutils literal"><span class="pre">HTTPConnection</span></code></a> object for a singlerequest/response exchange.</li></ul></td></tr></tbody></table>
This method should return a [`HTTPMessageDelegate`](# "tornado.httputil.HTTPMessageDelegate").
`on_close`(*server_conn*)[[source]](#)
This method is called when a connection has been closed.
| Parameters: | **server_conn** – is a server connection that has previously beenpassed to `start_request`. |
|-----|-----|
*class *`tornado.httputil.``HTTPMessageDelegate`[[source]](#)
Implement this interface to handle an HTTP request or response.
New in version 4.0.
`headers_received`(*start_line*, *headers*)[[source]](#)
Called when the HTTP headers have been received and parsed.
<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>start_line</strong> – a <a class="reference internal" href="#tornado.httputil.RequestStartLine" title="tornado.httputil.RequestStartLine"><code class="xref py py-obj docutils literal"><span class="pre">RequestStartLine</span></code></a> or <a class="reference internal" href="#tornado.httputil.ResponseStartLine" title="tornado.httputil.ResponseStartLine"><code class="xref py py-obj docutils literal"><span class="pre">ResponseStartLine</span></code></a>depending on whether this is a client or server message.</li><li><strong>headers</strong> – a <a class="reference internal" href="#tornado.httputil.HTTPHeaders" title="tornado.httputil.HTTPHeaders"><code class="xref py py-obj docutils literal"><span class="pre">HTTPHeaders</span></code></a> instance.</li></ul></td></tr></tbody></table>
Some [`HTTPConnection`](# "tornado.httputil.HTTPConnection") methods can only be called during`headers_received`.
May return a [`Future`](# "tornado.concurrent.Future"); if it does the body will not be readuntil it is done.
`data_received`(*chunk*)[[source]](#)
Called when a chunk of data has been received.
May return a [`Future`](# "tornado.concurrent.Future") for flow control.
`finish`()[[source]](#)
Called after the last chunk of data has been received.
`on_connection_close`()[[source]](#)
Called if the connection is closed without finishing the request.
If `headers_received` is called, either `finish` or`on_connection_close` will be called, but not both.
*class *`tornado.httputil.``HTTPConnection`[[source]](#)
Applications use this interface to write their responses.
New in version 4.0.
`write_headers`(*start_line*, *headers*, *chunk=None*, *callback=None*)[[source]](#)
Write an HTTP header block.
<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>start_line</strong> – a <a class="reference internal" href="#tornado.httputil.RequestStartLine" title="tornado.httputil.RequestStartLine"><code class="xref py py-obj docutils literal"><span class="pre">RequestStartLine</span></code></a> or <a class="reference internal" href="#tornado.httputil.ResponseStartLine" title="tornado.httputil.ResponseStartLine"><code class="xref py py-obj docutils literal"><span class="pre">ResponseStartLine</span></code></a>.</li><li><strong>headers</strong> – a <a class="reference internal" href="#tornado.httputil.HTTPHeaders" title="tornado.httputil.HTTPHeaders"><code class="xref py py-obj docutils literal"><span class="pre">HTTPHeaders</span></code></a> instance.</li><li><strong>chunk</strong> – the first (optional) chunk of data. This is an optimizationso that small responses can be written in the same call as theirheaders.</li><li><strong>callback</strong> – a callback to be run when the write is complete.</li></ul></td></tr></tbody></table>
The `version` field of `start_line` is ignored.
Returns a [`Future`](# "tornado.concurrent.Future") if no callback is given.
`write`(*chunk*, *callback=None*)[[source]](#)
Writes a chunk of body data.
The callback will be run when the write is complete. If no callbackis given, returns a Future.
`finish`()[[source]](#)
Indicates that the last body data has been written.
`tornado.httputil.``url_concat`(*url*, *args*)[[source]](#)
Concatenate url and arguments regardless of whetherurl has existing query parameters.
`args` may be either a dictionary or a list of key-value pairs(the latter allows for multiple values with the same key.
~~~
>>> url_concat("http://example.com/foo", dict(c="d"))
'http://example.com/foo?c=d'
>>> url_concat("http://example.com/foo?a=b", dict(c="d"))
'http://example.com/foo?a=b&c=d'
>>> url_concat("http://example.com/foo?a=b", [("c", "d"), ("c", "d2")])
'http://example.com/foo?a=b&c=d&c=d2'
~~~
*class *`tornado.httputil.``HTTPFile`[[source]](#)
Represents a file uploaded via a form.
For backwards compatibility, its instance attributes are alsoaccessible as dictionary keys.
- `filename`
- `body`
- `content_type`
`tornado.httputil.``parse_body_arguments`(*content_type*, *body*, *arguments*, *files*, *headers=None*)[[source]](#)
Parses a form request body.
Supports `application/x-www-form-urlencoded` and`multipart/form-data`. The `content_type` parameter should bea string and `body` should be a byte string. The `arguments`and `files` parameters are dictionaries that will be updatedwith the parsed contents.
`tornado.httputil.``parse_multipart_form_data`(*boundary*, *data*, *arguments*, *files*)[[source]](#)
Parses a `multipart/form-data` body.
The `boundary` and `data` parameters are both byte strings.The dictionaries given in the arguments and files parameterswill be updated with the contents of the body.
`tornado.httputil.``format_timestamp`(*ts*)[[source]](#)
Formats a timestamp in the format used by HTTP.
The argument may be a numeric timestamp as returned by [`time.time`](https://docs.python.org/3.4/library/time.html#time.time "(in Python v3.4)") [https://docs.python.org/3.4/library/time.html#time.time],a time tuple as returned by [`time.gmtime`](https://docs.python.org/3.4/library/time.html#time.gmtime "(in Python v3.4)") [https://docs.python.org/3.4/library/time.html#time.gmtime], or a [`datetime.datetime`](https://docs.python.org/3.4/library/datetime.html#datetime.datetime "(in Python v3.4)") [https://docs.python.org/3.4/library/datetime.html#datetime.datetime]object.
~~~
>>> format_timestamp(1359312200)
'Sun, 27 Jan 2013 18:43:20 GMT'
~~~
*class *`tornado.httputil.``RequestStartLine`
RequestStartLine(method, path, version)
`method`
Alias for field number 0
`path`
Alias for field number 1
`version`
Alias for field number 2
`tornado.httputil.``parse_request_start_line`(*line*)[[source]](#)
Returns a (method, path, version) tuple for an HTTP 1.x request line.
The response is a [`collections.namedtuple`](https://docs.python.org/3.4/library/collections.html#collections.namedtuple "(in Python v3.4)") [https://docs.python.org/3.4/library/collections.html#collections.namedtuple].
~~~
>>> parse_request_start_line("GET /foo HTTP/1.1")
RequestStartLine(method='GET', path='/foo', version='HTTP/1.1')
~~~
*class *`tornado.httputil.``ResponseStartLine`
ResponseStartLine(version, code, reason)
`code`
Alias for field number 1
`reason`
Alias for field number 2
`version`
Alias for field number 0
`tornado.httputil.``parse_response_start_line`(*line*)[[source]](#)
Returns a (version, code, reason) tuple for an HTTP 1.x response line.
The response is a [`collections.namedtuple`](https://docs.python.org/3.4/library/collections.html#collections.namedtuple "(in Python v3.4)") [https://docs.python.org/3.4/library/collections.html#collections.namedtuple].
~~~
>>> parse_response_start_line("HTTP/1.1 200 OK")
ResponseStartLine(version='HTTP/1.1', code=200, reason='OK')
~~~
`tornado.httputil.``split_host_and_port`(*netloc*)[[source]](#)
Returns `(host, port)` tuple from `netloc`.
Returned `port` will be `None` if not present.
New in version 4.1.
© 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