Cheroot HTTP Server
Cheroot is a high-performance, pure-Python HTTP server used by the CherryPy web framework, but it can also be used as a standalone WSGI server. It provides a robust and efficient way to serve web applications. The library is actively maintained, with the current version being 11.1.2, and aims for high stability and performance.
Warnings
- gotcha When serving WSGI applications, ensure that response status and headers adhere to PEP 3333. For Python 3, these must be `str` type but restricted to Latin-1 code points, not arbitrary Unicode.
- gotcha The `start_response` callable in a WSGI application must not transmit headers immediately. It should store them, and the server (Cheroot) will transmit them only after the first non-empty iterable yielded by the application or explicit `write()` call.
- gotcha By default, if the host specification is omitted during server instantiation, Cheroot will listen on all IPv4 interfaces (`0.0.0.0`). The default port, if not specified, is `8080`. Always explicitly configure the bind address for production environments.
Install
-
pip install cheroot -
pip install cheroot[zope]
Imports
- Server
from cheroot.wsgi import Server
- PathInfoDispatcher
from cheroot.wsgi import PathInfoDispatcher
Quickstart
import os
import time
from cheroot.wsgi import Server, PathInfoDispatcher
def simple_app(environ, start_response):
"""A simple WSGI application."""
status = '200 OK'
headers = [('Content-type', 'text/plain')]
start_response(status, headers)
return [b'Hello, Cheroot!\n']
def delayed_app(environ, start_response):
"""An application with a delay to demonstrate concurrency."""
time.sleep(2) # Simulate work
status = '200 OK'
headers = [('Content-type', 'text/plain')]
start_response(status, headers)
return [b'Hello after 2 seconds!\n']
# Map paths to WSGI applications
path_map = {
'/': simple_app,
'/delay': delayed_app,
}
dispatcher = PathInfoDispatcher(path_map)
# Configure the server
# Default host is 0.0.0.0, default port is 8080 if not specified
# Using 127.0.0.1 and a common testing port here
host = os.environ.get('CHERoot_HOST', '127.0.0.1')
port = int(os.environ.get('CHERoot_PORT', 8070))
server = Server((host, port), dispatcher)
print(f"Cheroot server starting on http://{host}:{port}/")
print("Access http://localhost:8070/ and http://localhost:8070/delay")
print("Press Ctrl+C to stop...")
try:
server.start()
except KeyboardInterrupt:
server.stop()
print("Cheroot server stopped.")