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.
-
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 theX-Real-Ip
orX-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 anX-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 fromRequestHandler.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.
A dictionary of Cookie.Morsel objects.
-
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 requestsConnection: keep-alive
). This means that the request callback must generate a properly-framed response, using either theContent-Length
header orTransfer-Encoding: chunked
. Applications that are unable to frame their responses properly should instead return aConnection: close
header in each response and passno_keep_alive=True
to theHTTPServer
constructor.If
xheaders
isTrue
, we support theX-Real-Ip
/X-Forwarded-For
andX-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. Theprotocol
argument can also be set tohttps
if Tornado is run behind an SSL-decoding proxy that does not set one of the supportedxheaders
.To make this server serve SSL traffic, send the
ssl_options
dictionary argument with the arguments required for thessl.wrap_socket
method, includingcertfile
andkeyfile
. (In Python 3.2+ you can pass anssl.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 ontornado.tcpserver.TCPServer
):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 theHTTPServer
.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 theHTTPServer
constructor.start
will always start the server on the default singletonIOLoop
.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 withtornado.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 thantornado.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).
-