tornado.httpserver — Non-blocking HTTP server¶
A non-blocking, single-threaded HTTP server.
Typical applications have little direct interaction with the
class except to start a server at the beginning of the process
(and even that is often done indirectly via
Changed in version 4.0: The
HTTPRequest class that used to live in this module has been moved
tornado.httputil.HTTPServerRequest. The old name remains as an alias.
- class tornado.httpserver.HTTPServer(request_callback: Union[httputil.HTTPServerConnectionDelegate, Callable[[httputil.HTTPServerRequest], None]], no_keep_alive: bool = False, xheaders: bool = False, ssl_options: Union[Dict[str, Any], ssl.SSLContext] = None, protocol: Optional[str] = None, decompress_request: bool = False, chunk_size: Optional[int] = None, max_header_size: Optional[int] = None, idle_connection_timeout: Optional[float] = None, body_timeout: Optional[float] = None, max_body_size: Optional[int] = None, max_buffer_size: Optional[int] = None, trusted_downstream: Optional[List[str]] = None)¶
A non-blocking, single-threaded HTTP server.
A server is defined by a subclass of
HTTPServerConnectionDelegate, or, for backwards compatibility, a callback that takes an
HTTPServerRequestas an argument. The delegate is usually a
HTTPServersupports keep-alive connections by default (automatically for HTTP/1.1, or for HTTP/1.0 when the client requests
True, we support the
X-Forwarded-Protoheaders, 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
protocolargument can also be set to
httpsif Tornado is run behind an SSL-decoding proxy that does not set one of the supported
By default, when parsing the
X-Forwarded-Forheader, Tornado will select the last (i.e., the closest) address on the list of hosts as the remote host IP address. To select the next server in the chain, a list of trusted downstream hosts may be passed as the
trusted_downstreamargument. These hosts will be skipped when parsing the
To make this server serve SSL traffic, send the
ssl_optionskeyword argument with an
ssl.SSLContextobject. For compatibility with older versions of Python
ssl_optionsmay also be a dictionary of keyword arguments for the
ssl_ctx = ssl.create_default_context(ssl.Purpose.CLIENT_AUTH) ssl_ctx.load_cert_chain(os.path.join(data_dir, "mydomain.crt"), os.path.join(data_dir, "mydomain.key")) HTTPServer(application, ssl_options=ssl_ctx)
async def main(): server = HTTPServer() server.listen(8888) await asyncio.Event.wait() asyncio.run(main())
While this example does not create multiple processes on its own, when the
reuse_port=Trueargument is passed to
listen()you can run the program multiple times to create a multi-process service.
sockets = bind_sockets(8888) tornado.process.fork_processes(0) async def post_fork_main(): server = HTTPServer() server.add_sockets(sockets) await asyncio.Event().wait() asyncio.run(post_fork_main())
add_socketsinterface is more complicated, but it can be used with
tornado.process.fork_processesto run a multi-process service with all worker processes forked from a single parent.
add_socketscan also be used in single-process servers if you want to create your listening sockets in some way other than
Note that when using this pattern, nothing that touches the event loop can be run before
server = HTTPServer() server.bind(8888) server.start(0) # Forks multiple sub-processes IOLoop.current().start()
This pattern is deprecated because it requires interfaces in the
asynciomodule that have been deprecated since Python 3.10. Support for creating multiple processes in the
startmethod will be removed in a future version of Tornado.
Changed in version 4.0: Added
max_body_sizearguments. Added support for
Changed in version 4.1:
HTTPServerConnectionDelegate.start_requestis now called with two arguments
(server_conn, request_conn)(in accordance with the documentation) instead of one
Changed in version 4.5: Added the
Changed in version 5.0: The
io_loopargument has been removed.
The public interface of this class is mostly inherited from
TCPServerand is documented under that class.
- coroutine close_all_connections() None ¶
Close all open connections and asynchronously wait for them to finish.
This method is used in combination with
stopto support clean shutdowns (especially for unittests). Typical usage would call
stop()first to stop accepting new connections, then
await close_all_connections()to wait for existing connections to finish.
This method does not currently close open websocket connections.
Note that this method is a coroutine and must be called with