tornado.httpserver — Non-blocking HTTP server

A non-blocking, single-threaded HTTP server.

Typical applications have little direct interaction with the HTTPServer class except to start a server at the beginning of the process (and even that is often done indirectly via tornado.web.Application.listen).

This module also defines the HTTPRequest class which is exposed via tornado.web.RequestHandler.request.

HTTPRequest objects

class tornado.httpserver.HTTPRequest(method, uri, version='HTTP/1.0', headers=None, body=None, remote_ip=None, protocol=None, host=None, files=None, connection=None)[source]

A single HTTP request.

All attributes are type str unless otherwise noted.

method

HTTP request method, e.g. “GET” or “POST”

uri

The requested uri.

path

The path portion of uri

query

The query portion of uri

version

HTTP version specified in request, e.g. “HTTP/1.1”

headers

HTTPHeaders dictionary-like object for request headers. Acts like a case-insensitive dictionary with additional methods for repeated headers.

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 balancer in 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 if reported 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, which maps arguments names to lists of values (to support multiple values for individual names). Names are of type str, while arguments are byte strings. Note that this is different from RequestHandler.get_argument, which returns argument values as unicode strings.

files

File uploads are available in the files property, which maps file names to lists of HTTPFile.

connection

An HTTP request is attached to a single HTTP connection, which can be accessed through the “connection” attribute. Since connections are typically kept open in HTTP/1.1, multiple requests can be handled sequentially on a single connection.

supports_http_1_1()[source]

Returns True if this request supports HTTP/1.1 semantics

cookies[source]

A dictionary of Cookie.Morsel objects.

write(chunk, callback=None)[source]

Writes the given chunk to the response stream.

finish()[source]

Finishes this HTTP request on the open connection.

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 must have been constructed with cert_reqs set in ssl_options, e.g.:

server = HTTPServer(app,
    ssl_options=dict(
        certfile="foo.crt",
        keyfile="foo.key",
        cert_reqs=ssl.CERT_REQUIRED,
        ca_certs="cacert.crt"))

By default, the return value is a dictionary (or None, if no client certificate is present). If binary_form is true, a DER-encoded form of the certificate is returned instead. See SSLSocket.getpeercert() in the standard library for more details. http://docs.python.org/library/ssl.html#sslsocket-objects

HTTP Server

class tornado.httpserver.HTTPServer(request_callback, no_keep_alive=False, io_loop=None, xheaders=False, ssl_options=None, protocol=None, **kwargs)[source]

A non-blocking, single-threaded HTTP server.

A server is defined by a request callback that takes an HTTPRequest instance as an argument and writes a valid HTTP response with HTTPRequest.write. HTTPRequest.finish finishes the request (but does not necessarily close the connection in the case of HTTP/1.1 keep-alive requests). A simple example server that echoes back the URI you requested:

import tornado.httpserver
import tornado.ioloop

def handle_request(request):
   message = "You requested %s\n" % request.uri
   request.write("HTTP/1.1 200 OK\r\nContent-Length: %d\r\n\r\n%s" % (
                 len(message), message))
   request.finish()

http_server = tornado.httpserver.HTTPServer(handle_request)
http_server.listen(8888)
tornado.ioloop.IOLoop.instance().start()

HTTPServer is a very basic connection handler. It parses the request headers and body, but the request callback is responsible for producing the response exactly as it will appear on the wire. This affords maximum flexibility for applications to implement whatever parts of HTTP responses are required.

HTTPServer supports keep-alive connections by default (automatically for HTTP/1.1, or for HTTP/1.0 when the client requests Connection: keep-alive). This means that the request callback must generate a properly-framed response, using either the Content-Length header or Transfer-Encoding: chunked. Applications that are unable to frame their responses properly should instead return a Connection: close header in each response and pass no_keep_alive=True to the HTTPServer constructor.

If xheaders is True, we support the X-Real-Ip/X-Forwarded-For and X-Scheme/X-Forwarded-Proto headers, which override the remote IP and URI scheme/protocol for all requests. These headers are useful when running Tornado behind a reverse proxy or load balancer. The protocol argument can also be set to https if Tornado is run behind an SSL-decoding proxy that does not set one of the supported xheaders.

To make this server serve SSL traffic, send the ssl_options dictionary argument with the arguments required for the ssl.wrap_socket method, including certfile and keyfile. (In Python 3.2+ you can pass an ssl.SSLContext object instead of a dict):

HTTPServer(applicaton, ssl_options={
    "certfile": os.path.join(data_dir, "mydomain.crt"),
    "keyfile": os.path.join(data_dir, "mydomain.key"),
})

HTTPServer initialization follows one of three patterns (the initialization methods are defined on tornado.tcpserver.TCPServer):

  1. listen: simple single-process:

    server = HTTPServer(app)
    server.listen(8888)
    IOLoop.instance().start()
    

    In many cases, tornado.web.Application.listen can be used to avoid the need to explicitly create the HTTPServer.

  2. bind/start: simple multi-process:

    server = HTTPServer(app)
    server.bind(8888)
    server.start(0)  # Forks multiple sub-processes
    IOLoop.instance().start()
    

    When using this interface, an IOLoop must not be passed to the HTTPServer constructor. start will always start the server on the default singleton IOLoop.

  3. add_sockets: advanced multi-process:

    sockets = tornado.netutil.bind_sockets(8888)
    tornado.process.fork_processes(0)
    server = HTTPServer(app)
    server.add_sockets(sockets)
    IOLoop.instance().start()
    

    The add_sockets interface is more complicated, but it can be used with tornado.process.fork_processes to give you more flexibility in when the fork happens. add_sockets can also be used in single-process servers if you want to create your listening sockets in some way other than tornado.netutil.bind_sockets.

class tornado.httpserver.HTTPConnection(stream, address, request_callback, no_keep_alive=False, xheaders=False, protocol=None)[source]

Handles a connection to an HTTP client, executing HTTP requests.

We parse HTTP headers and bodies, and execute the request callback until the HTTP conection is closed.

set_close_callback(callback)[source]

Sets a callback that will be run when the connection is closed.

Use this instead of accessing HTTPConnection.stream.set_close_callback directly (which was the recommended approach prior to Tornado 3.0).

write(chunk, callback=None)[source]

Writes a chunk of output to the stream.

finish()[source]

Finishes the request.