cherrypy.wsgiserver package

Submodules

cherrypy.wsgiserver.ssl_builtin module

A library for integrating Python’s builtin ssl library with CherryPy.

The ssl module must be importable for SSL functionality.

To use this module, set CherryPyWSGIServer.ssl_adapter to an instance of BuiltinSSLAdapter.

class cherrypy.wsgiserver.ssl_builtin.BuiltinSSLAdapter(certificate, private_key, certificate_chain=None)

Bases: cherrypy.wsgiserver.wsgiserver2.SSLAdapter

A wrapper for integrating Python’s builtin ssl module with CherryPy.

bind(sock)

Wrap and return the given socket.

certificate = None

The filename of the server SSL certificate.

get_environ(sock)

Create WSGI environ entries to be merged into each request.

makefile(sock, mode='r', bufsize=8192)
private_key = None

The filename of the server’s private key file.

wrap(sock)

Wrap and return the given socket, plus WSGI environ entries.

cherrypy.wsgiserver.ssl_pyopenssl module

A library for integrating pyOpenSSL with CherryPy.

The OpenSSL module must be importable for SSL functionality. You can obtain it from here.

To use this module, set CherryPyWSGIServer.ssl_adapter to an instance of SSLAdapter. There are two ways to use SSL:

Method One

  • ssl_adapter.context: an instance of SSL.Context.

If this is not None, it is assumed to be an SSL.Context instance, and will be passed to SSL.Connection on bind(). The developer is responsible for forming a valid Context object. This approach is to be preferred for more flexibility, e.g. if the cert and key are streams instead of files, or need decryption, or SSL.SSLv3_METHOD is desired instead of the default SSL.SSLv23_METHOD, etc. Consult the pyOpenSSL documentation for complete options.

Method Two (shortcut)

  • ssl_adapter.certificate: the filename of the server SSL certificate.
  • ssl_adapter.private_key: the filename of the server’s private key file.

Both are None by default. If ssl_adapter.context is None, but .private_key and .certificate are both given and valid, they will be read, and the context will be automatically created from them.

class cherrypy.wsgiserver.ssl_pyopenssl.SSLConnection(*args)

A thread-safe wrapper for an SSL.Connection.

*args: the arguments to create the wrapped SSL.Connection(*args).

accept(*args)
bind(*args)
close(*args)
connect(*args)
connect_ex(*args)
f = 'gettimeout'
fileno(*args)
get_app_data(*args)
get_cipher_list(*args)
get_context(*args)
get_peer_certificate(*args)
getpeername(*args)
getsockname(*args)
getsockopt(*args)
gettimeout(*args)
listen(*args)
makefile(*args)
pending(*args)
read(*args)
recv(*args)
renegotiate(*args)
send(*args)
sendall(*args)
set_accept_state(*args)
set_app_data(*args)
set_connect_state(*args)
setblocking(*args)
setsockopt(*args)
settimeout(*args)
shutdown(*args)
sock_shutdown(*args)
state_string(*args)
want_read(*args)
want_write(*args)
write(*args)
class cherrypy.wsgiserver.ssl_pyopenssl.SSL_fileobject(*args, **kwargs)

Bases: cherrypy.wsgiserver.wsgiserver2.CP_fileobject

SSL file object attached to a socket object.

recv(size)
send(*args, **kwargs)
sendall(*args, **kwargs)
ssl_retry = 0.01
ssl_timeout = 3
class cherrypy.wsgiserver.ssl_pyopenssl.pyOpenSSLAdapter(certificate, private_key, certificate_chain=None)

Bases: cherrypy.wsgiserver.wsgiserver2.SSLAdapter

A wrapper for integrating pyOpenSSL with CherryPy.

bind(sock)

Wrap and return the given socket.

certificate = None

The filename of the server SSL certificate.

certificate_chain = None

Optional. The filename of CA’s intermediate certificate bundle.

This is needed for cheaper “chained root” SSL certificates, and should be left as None if not required.

context = None

An instance of SSL.Context.

get_context()

Return an SSL.Context from self attributes.

get_environ()

Return WSGI environ entries to be merged into each request.

makefile(sock, mode='r', bufsize=-1)
private_key = None

The filename of the server’s private key file.

wrap(sock)

Wrap and return the given socket, plus WSGI environ entries.

cherrypy.wsgiserver.wsgiserver2 module

A high-speed, production ready, thread pooled, generic HTTP server.

Simplest example on how to use this module directly (without using CherryPy’s application machinery):

from cherrypy import wsgiserver

def my_crazy_app(environ, start_response):
    status = '200 OK'
    response_headers = [('Content-type','text/plain')]
    start_response(status, response_headers)
    return ['Hello world!']

server = wsgiserver.CherryPyWSGIServer(
            ('0.0.0.0', 8070), my_crazy_app,
            server_name='www.cherrypy.example')
server.start()

The CherryPy WSGI server can serve as many WSGI applications as you want in one instance by using a WSGIPathInfoDispatcher:

d = WSGIPathInfoDispatcher({'/': my_crazy_app, '/blog': my_blog_app})
server = wsgiserver.CherryPyWSGIServer(('0.0.0.0', 80), d)

Want SSL support? Just set server.ssl_adapter to an SSLAdapter instance.

This won’t call the CherryPy engine (application side) at all, only the HTTP server, which is independent from the rest of CherryPy. Don’t let the name “CherryPyWSGIServer” throw you; the name merely reflects its origin, not its coupling.

For those of you wanting to understand internals of this module, here’s the basic call flow. The server’s listening thread runs a very tight loop, sticking incoming connections onto a Queue:

server = CherryPyWSGIServer(...)
server.start()
while True:
    tick()
    # This blocks until a request comes in:
    child = socket.accept()
    conn = HTTPConnection(child, ...)
    server.requests.put(conn)

Worker threads are kept in a pool and poll the Queue, popping off and then handling each connection in turn. Each connection can consist of an arbitrary number of requests and their responses, so we run a nested loop:

while True:
    conn = server.requests.get()
    conn.communicate()
    ->  while True:
            req = HTTPRequest(...)
            req.parse_request()
            ->  # Read the Request-Line, e.g. "GET /page HTTP/1.1"
                req.rfile.readline()
                read_headers(req.rfile, req.inheaders)
            req.respond()
            ->  response = app(...)
                try:
                    for chunk in response:
                        if chunk:
                            req.write(chunk)
                finally:
                    if hasattr(response, "close"):
                        response.close()
            if req.close_connection:
                return
class cherrypy.wsgiserver.wsgiserver2.HTTPRequest(server, conn)

Bases: object

An HTTP Request (and response).

A single HTTP connection may consist of multiple request/response pairs.

chunked_write = False

If True, output will be encoded with the “chunked” transfer-coding.

This value is set automatically inside send_headers.

close_connection = False

Signals the calling Connection that the request should close. This does not imply an error! The client and/or server may each request that the connection be closed.

conn = None

The HTTPConnection object on which this request connected.

inheaders = {}

A dict of request headers.

outheaders = []

A list of header tuples to write in the response.

parse_request()

Parse the next HTTP request start-line and message-headers.

parse_request_uri(uri)

Parse a Request-URI into (scheme, authority, path).

Note that Request-URI’s must be one of:

Request-URI    = "*" | absoluteURI | abs_path | authority

Therefore, a Request-URI which starts with a double forward-slash cannot be a “net_path”:

net_path      = "//" authority [ abs_path ]

Instead, it must be interpreted as an “abs_path” with an empty first path segment:

abs_path      = "/"  path_segments
path_segments = segment *( "/" segment )
segment       = *pchar *( ";" param )
param         = *pchar
read_request_headers()

Read self.rfile into self.inheaders. Return success.

read_request_line()
ready = False

When True, the request has been parsed and is ready to begin generating the response. When False, signals the calling Connection that the response should not be generated and the connection should close.

respond()

Call the gateway and write its iterable output.

send_headers()

Assert, process, and send the HTTP response message-headers.

You must set self.status, and self.outheaders before calling this.

server = None

The HTTPServer object which is receiving this request.

simple_response(status, msg='')

Write a simple response back to the client.

write(chunk)

Write unbuffered data to the client.

class cherrypy.wsgiserver.wsgiserver2.HTTPConnection(server, sock, makefile=<class 'cherrypy.wsgiserver.wsgiserver2.CP_fileobject'>)

Bases: object

An HTTP connection (active socket).

server: the Server object which received this connection. socket: the raw socket object (usually TCP) for this connection. makefile: a fileobject class for reading from the socket.

RequestHandlerClass

alias of HTTPRequest

close()

Close the socket underlying this connection.

communicate()

Read each request and respond appropriately.

linger = False
rbufsize = -1
remote_addr = None
remote_port = None
ssl_env = None
wbufsize = -1
class cherrypy.wsgiserver.wsgiserver2.HTTPServer(bind_addr, gateway, minthreads=10, maxthreads=-1, server_name=None)

Bases: object

An HTTP server.

ConnectionClass

The class to use for handling HTTP connections.

alias of HTTPConnection

bind(family, type, proto=0)

Create (or recreate) the actual socket object.

bind_addr

The interface on which to listen for connections.

For TCP sockets, a (host, port) tuple. Host values may be any IPv4 or IPv6 address, or any valid hostname. The string ‘localhost’ is a synonym for ‘127.0.0.1’ (or ‘::1’, if your hosts file prefers IPv6). The string ‘0.0.0.0’ is a special IPv4 entry meaning “any active interface” (INADDR_ANY), and ‘::’ is the similar IN6ADDR_ANY for IPv6. The empty string or None are not allowed.

For UNIX sockets, supply the filename as a string.

clear_stats()
error_log(msg='', level=20, traceback=False)
gateway = None

A Gateway instance.

interrupt

Set this to an Exception instance to interrupt the server.

max_request_body_size = 0

The maximum size, in bytes, for request bodies, or 0 for no limit.

max_request_header_size = 0

The maximum size, in bytes, for request headers, or 0 for no limit.

maxthreads = None

The maximum number of worker threads to create (default -1 = no limit).

minthreads = None

The minimum number of worker threads to create (default 10).

nodelay = True

If True (the default since 3.1), sets the TCP_NODELAY socket option.

protocol = 'HTTP/1.1'

The version string to write in the Status-Line of all HTTP responses.

For example, “HTTP/1.1” is the default. This also limits the supported features used in the response.

ready = False

An internal flag which marks whether the socket is accepting connections

request_queue_size = 5

The ‘backlog’ arg to socket.listen(); max queued connections (default 5).

runtime()
server_name = None

The name of the server; defaults to socket.gethostname().

shutdown_timeout = 5

The total time, in seconds, to wait for worker threads to cleanly exit.

software = None

The value to set for the SERVER_SOFTWARE entry in the WSGI environ.

If None, this defaults to '%s Server' % self.version.

ssl_adapter = None

An instance of SSLAdapter (or a subclass).

You must have the corresponding SSL driver library installed.

start()

Run the server forever.

stop()

Gracefully shutdown a server that is serving forever.

tick()

Accept a new connection and put it on the Queue.

timeout = 10

The timeout in seconds for accepted connections (default 10).

version = 'CherryPy/3.3.0'

A version string for the HTTPServer.

class cherrypy.wsgiserver.wsgiserver2.SizeCheckWrapper(rfile, maxlen)

Bases: object

Wraps a file-like object, raising MaxSizeExceeded if too large.

close()
next()
read(size=None)
readline(size=None)
readlines(sizehint=0)
class cherrypy.wsgiserver.wsgiserver2.KnownLengthRFile(rfile, content_length)

Bases: object

Wraps a file-like object, returning an empty string when exhausted.

close()
read(size=None)
readline(size=None)
readlines(sizehint=0)
class cherrypy.wsgiserver.wsgiserver2.ChunkedRFile(rfile, maxlen, bufsize=8192)

Bases: object

Wraps a file-like object, returning an empty string when exhausted.

This class is intended to provide a conforming wsgi.input value for request entities that have been encoded with the ‘chunked’ transfer encoding.

close()
read(size=None)
read_trailer_lines()
readline(size=None)
readlines(sizehint=0)
class cherrypy.wsgiserver.wsgiserver2.CP_fileobject(*args, **kwargs)

Bases: socket._fileobject

Faux file object attached to a socket object.

flush()
read(size=-1)
readline(size=-1)
recv(size)
send(data)
sendall(data)

Sendall for non-blocking sockets.

exception cherrypy.wsgiserver.wsgiserver2.MaxSizeExceeded

Bases: exceptions.Exception

exception cherrypy.wsgiserver.wsgiserver2.NoSSLError

Bases: exceptions.Exception

Exception raised when a client speaks HTTP to an HTTPS socket.

exception cherrypy.wsgiserver.wsgiserver2.FatalSSLAlert

Bases: exceptions.Exception

Exception raised when the SSL implementation signals a fatal alert.

class cherrypy.wsgiserver.wsgiserver2.WorkerThread(server)

Bases: threading.Thread

Thread which continuously polls a Queue for Connection objects.

Due to the timing issues of polling a Queue, a WorkerThread does not check its own ‘ready’ flag after it has started. To stop the thread, it is necessary to stick a _SHUTDOWNREQUEST object onto the Queue (one for each running WorkerThread).

conn = None

The current connection pulled off the Queue, or None.

ready = False

A simple flag for the calling server to know when this thread has begun polling the Queue.

run()
server = None

The HTTP Server which spawned this thread, and which owns the Queue and is placing active connections into it.

class cherrypy.wsgiserver.wsgiserver2.ThreadPool(server, min=10, max=-1)

Bases: object

A Request Queue for an HTTPServer which pools threads.

ThreadPool objects must provide min, get(), put(obj), start() and stop(timeout) attributes.

grow(amount)

Spawn new worker threads (not above self.max).

idle

Number of worker threads which are idle. Read-only.

put(obj)
qsize
shrink(amount)

Kill off worker threads (not below self.min).

start()

Start the pool of threads.

stop(timeout=5)
class cherrypy.wsgiserver.wsgiserver2.SSLAdapter(certificate, private_key, certificate_chain=None)

Bases: object

Base class for SSL driver library adapters.

Required methods:

  • wrap(sock) -> (wrapped socket, ssl environ dict)
  • makefile(sock, mode='r', bufsize=DEFAULT_BUFFER_SIZE) -> socket file object
makefile(sock, mode='r', bufsize=-1)
wrap(sock)
class cherrypy.wsgiserver.wsgiserver2.CherryPyWSGIServer(bind_addr, wsgi_app, numthreads=10, server_name=None, max=-1, request_queue_size=5, timeout=10, shutdown_timeout=5)

Bases: cherrypy.wsgiserver.wsgiserver2.HTTPServer

A subclass of HTTPServer which calls a WSGI application.

numthreads
wsgi_version = (1, 0)

The version of WSGI to produce.

class cherrypy.wsgiserver.wsgiserver2.Gateway(req)

Bases: object

A base class to interface HTTPServer with other systems, such as WSGI.

respond()

Process the current request. Must be overridden in a subclass.

class cherrypy.wsgiserver.wsgiserver2.WSGIGateway(req)

Bases: cherrypy.wsgiserver.wsgiserver2.Gateway

A base class to interface HTTPServer with WSGI.

get_environ()

Return a new environ dict targeting the given wsgi.version

respond()

Process the current request.

start_response(status, headers, exc_info=None)

WSGI callable to begin the HTTP response.

write(chunk)

WSGI callable to write unbuffered data to the client.

This method is also used internally by start_response (to write data from the iterable returned by the WSGI application).

class cherrypy.wsgiserver.wsgiserver2.WSGIGateway_10(req)

Bases: cherrypy.wsgiserver.wsgiserver2.WSGIGateway

A Gateway class to interface HTTPServer with WSGI 1.0.x.

get_environ()

Return a new environ dict targeting the given wsgi.version

class cherrypy.wsgiserver.wsgiserver2.WSGIGateway_u0(req)

Bases: cherrypy.wsgiserver.wsgiserver2.WSGIGateway_10

A Gateway class to interface HTTPServer with WSGI u.0.

WSGI u.0 is an experimental protocol, which uses unicode for keys and values in both Python 2 and Python 3.

get_environ()

Return a new environ dict targeting the given wsgi.version

class cherrypy.wsgiserver.wsgiserver2.WSGIPathInfoDispatcher(apps)

Bases: object

A WSGI dispatcher for dispatch based on the PATH_INFO.

apps: a dict or list of (path_prefix, app) pairs.

cherrypy.wsgiserver.wsgiserver2.get_ssl_adapter_class(name='pyopenssl')

Return an SSL adapter class for the given name.

cherrypy.wsgiserver.wsgiserver3 module

A high-speed, production ready, thread pooled, generic HTTP server.

Simplest example on how to use this module directly (without using CherryPy’s application machinery):

from cherrypy import wsgiserver

def my_crazy_app(environ, start_response):
    status = '200 OK'
    response_headers = [('Content-type','text/plain')]
    start_response(status, response_headers)
    return ['Hello world!']

server = wsgiserver.CherryPyWSGIServer(
            ('0.0.0.0', 8070), my_crazy_app,
            server_name='www.cherrypy.example')
server.start()

The CherryPy WSGI server can serve as many WSGI applications as you want in one instance by using a WSGIPathInfoDispatcher:

d = WSGIPathInfoDispatcher({'/': my_crazy_app, '/blog': my_blog_app})
server = wsgiserver.CherryPyWSGIServer(('0.0.0.0', 80), d)

Want SSL support? Just set server.ssl_adapter to an SSLAdapter instance.

This won’t call the CherryPy engine (application side) at all, only the HTTP server, which is independent from the rest of CherryPy. Don’t let the name “CherryPyWSGIServer” throw you; the name merely reflects its origin, not its coupling.

For those of you wanting to understand internals of this module, here’s the basic call flow. The server’s listening thread runs a very tight loop, sticking incoming connections onto a Queue:

server = CherryPyWSGIServer(...)
server.start()
while True:
    tick()
    # This blocks until a request comes in:
    child = socket.accept()
    conn = HTTPConnection(child, ...)
    server.requests.put(conn)

Worker threads are kept in a pool and poll the Queue, popping off and then handling each connection in turn. Each connection can consist of an arbitrary number of requests and their responses, so we run a nested loop:

while True:
    conn = server.requests.get()
    conn.communicate()
    ->  while True:
            req = HTTPRequest(...)
            req.parse_request()
            ->  # Read the Request-Line, e.g. "GET /page HTTP/1.1"
                req.rfile.readline()
                read_headers(req.rfile, req.inheaders)
            req.respond()
            ->  response = app(...)
                try:
                    for chunk in response:
                        if chunk:
                            req.write(chunk)
                finally:
                    if hasattr(response, "close"):
                        response.close()
            if req.close_connection:
                return
class cherrypy.wsgiserver.wsgiserver3.HTTPRequest(server, conn)

Bases: object

An HTTP Request (and response).

A single HTTP connection may consist of multiple request/response pairs.

chunked_write = False

If True, output will be encoded with the “chunked” transfer-coding.

This value is set automatically inside send_headers.

close_connection = False

Signals the calling Connection that the request should close. This does not imply an error! The client and/or server may each request that the connection be closed.

conn = None

The HTTPConnection object on which this request connected.

inheaders = {}

A dict of request headers.

outheaders = []

A list of header tuples to write in the response.

parse_request()

Parse the next HTTP request start-line and message-headers.

parse_request_uri(uri)

Parse a Request-URI into (scheme, authority, path).

Note that Request-URI’s must be one of:

Request-URI    = "*" | absoluteURI | abs_path | authority

Therefore, a Request-URI which starts with a double forward-slash cannot be a “net_path”:

net_path      = "//" authority [ abs_path ]

Instead, it must be interpreted as an “abs_path” with an empty first path segment:

abs_path      = "/"  path_segments
path_segments = segment *( "/" segment )
segment       = *pchar *( ";" param )
param         = *pchar
read_request_headers()

Read self.rfile into self.inheaders. Return success.

read_request_line()
ready = False

When True, the request has been parsed and is ready to begin generating the response. When False, signals the calling Connection that the response should not be generated and the connection should close.

respond()

Call the gateway and write its iterable output.

send_headers()

Assert, process, and send the HTTP response message-headers.

You must set self.status, and self.outheaders before calling this.

server = None

The HTTPServer object which is receiving this request.

simple_response(status, msg='')

Write a simple response back to the client.

unquote_bytes(path)

takes quoted string and unquotes % encoded values

write(chunk)

Write unbuffered data to the client.

class cherrypy.wsgiserver.wsgiserver3.HTTPConnection(server, sock, makefile=<function CP_makefile at 0x7f362337d668>)

Bases: object

An HTTP connection (active socket).

server: the Server object which received this connection. socket: the raw socket object (usually TCP) for this connection. makefile: a fileobject class for reading from the socket.

RequestHandlerClass

alias of HTTPRequest

close()

Close the socket underlying this connection.

communicate()

Read each request and respond appropriately.

linger = False
rbufsize = 8192
remote_addr = None
remote_port = None
ssl_env = None
wbufsize = 8192
class cherrypy.wsgiserver.wsgiserver3.HTTPServer(bind_addr, gateway, minthreads=10, maxthreads=-1, server_name=None)

Bases: object

An HTTP server.

ConnectionClass

The class to use for handling HTTP connections.

alias of HTTPConnection

bind(family, type, proto=0)

Create (or recreate) the actual socket object.

bind_addr

The interface on which to listen for connections.

For TCP sockets, a (host, port) tuple. Host values may be any IPv4 or IPv6 address, or any valid hostname. The string ‘localhost’ is a synonym for ‘127.0.0.1’ (or ‘::1’, if your hosts file prefers IPv6). The string ‘0.0.0.0’ is a special IPv4 entry meaning “any active interface” (INADDR_ANY), and ‘::’ is the similar IN6ADDR_ANY for IPv6. The empty string or None are not allowed.

For UNIX sockets, supply the filename as a string.

clear_stats()
error_log(msg='', level=20, traceback=False)
gateway = None

A Gateway instance.

interrupt

Set this to an Exception instance to interrupt the server.

max_request_body_size = 0

The maximum size, in bytes, for request bodies, or 0 for no limit.

max_request_header_size = 0

The maximum size, in bytes, for request headers, or 0 for no limit.

maxthreads = None

The maximum number of worker threads to create (default -1 = no limit).

minthreads = None

The minimum number of worker threads to create (default 10).

nodelay = True

If True (the default since 3.1), sets the TCP_NODELAY socket option.

protocol = 'HTTP/1.1'

The version string to write in the Status-Line of all HTTP responses.

For example, “HTTP/1.1” is the default. This also limits the supported features used in the response.

ready = False

An internal flag which marks whether the socket is accepting connections.

request_queue_size = 5

The ‘backlog’ arg to socket.listen(); max queued connections (default 5).

runtime()
server_name = None

The name of the server; defaults to socket.gethostname().

shutdown_timeout = 5

The total time, in seconds, to wait for worker threads to cleanly exit.

software = None

The value to set for the SERVER_SOFTWARE entry in the WSGI environ.

If None, this defaults to '%s Server' % self.version.

ssl_adapter = None

An instance of SSLAdapter (or a subclass).

You must have the corresponding SSL driver library installed.

start()

Run the server forever.

stop()

Gracefully shutdown a server that is serving forever.

tick()

Accept a new connection and put it on the Queue.

timeout = 10

The timeout in seconds for accepted connections (default 10).

version = 'CherryPy/3.3.0'

A version string for the HTTPServer.

class cherrypy.wsgiserver.wsgiserver3.SizeCheckWrapper(rfile, maxlen)

Bases: object

Wraps a file-like object, raising MaxSizeExceeded if too large.

close()
next()
read(size=None)
readline(size=None)
readlines(sizehint=0)
class cherrypy.wsgiserver.wsgiserver3.KnownLengthRFile(rfile, content_length)

Bases: object

Wraps a file-like object, returning an empty string when exhausted.

close()
read(size=None)
readline(size=None)
readlines(sizehint=0)
class cherrypy.wsgiserver.wsgiserver3.ChunkedRFile(rfile, maxlen, bufsize=8192)

Bases: object

Wraps a file-like object, returning an empty string when exhausted.

This class is intended to provide a conforming wsgi.input value for request entities that have been encoded with the ‘chunked’ transfer encoding.

close()
read(size=None)
read_trailer_lines()
readline(size=None)
readlines(sizehint=0)
cherrypy.wsgiserver.wsgiserver3.CP_makefile(sock, mode='r', bufsize=8192)
exception cherrypy.wsgiserver.wsgiserver3.MaxSizeExceeded

Bases: exceptions.Exception

exception cherrypy.wsgiserver.wsgiserver3.NoSSLError

Bases: exceptions.Exception

Exception raised when a client speaks HTTP to an HTTPS socket.

exception cherrypy.wsgiserver.wsgiserver3.FatalSSLAlert

Bases: exceptions.Exception

Exception raised when the SSL implementation signals a fatal alert.

class cherrypy.wsgiserver.wsgiserver3.WorkerThread(server)

Bases: threading.Thread

Thread which continuously polls a Queue for Connection objects.

Due to the timing issues of polling a Queue, a WorkerThread does not check its own ‘ready’ flag after it has started. To stop the thread, it is necessary to stick a _SHUTDOWNREQUEST object onto the Queue (one for each running WorkerThread).

conn = None

The current connection pulled off the Queue, or None.

ready = False

A simple flag for the calling server to know when this thread has begun polling the Queue.

run()
server = None

The HTTP Server which spawned this thread, and which owns the Queue and is placing active connections into it.

class cherrypy.wsgiserver.wsgiserver3.ThreadPool(server, min=10, max=-1)

Bases: object

A Request Queue for an HTTPServer which pools threads.

ThreadPool objects must provide min, get(), put(obj), start() and stop(timeout) attributes.

grow(amount)

Spawn new worker threads (not above self.max).

idle

Number of worker threads which are idle. Read-only.

put(obj)
qsize
shrink(amount)

Kill off worker threads (not below self.min).

start()

Start the pool of threads.

stop(timeout=5)
class cherrypy.wsgiserver.wsgiserver3.SSLAdapter(certificate, private_key, certificate_chain=None)

Bases: object

Base class for SSL driver library adapters.

Required methods:

  • wrap(sock) -> (wrapped socket, ssl environ dict)
  • makefile(sock, mode='r', bufsize=DEFAULT_BUFFER_SIZE) -> socket file object
makefile(sock, mode='r', bufsize=8192)
wrap(sock)
class cherrypy.wsgiserver.wsgiserver3.CherryPyWSGIServer(bind_addr, wsgi_app, numthreads=10, server_name=None, max=-1, request_queue_size=5, timeout=10, shutdown_timeout=5)

Bases: cherrypy.wsgiserver.wsgiserver3.HTTPServer

A subclass of HTTPServer which calls a WSGI application.

numthreads
wsgi_version = (1, 0)

The version of WSGI to produce.

class cherrypy.wsgiserver.wsgiserver3.Gateway(req)

Bases: object

A base class to interface HTTPServer with other systems, such as WSGI.

respond()

Process the current request. Must be overridden in a subclass.

class cherrypy.wsgiserver.wsgiserver3.WSGIGateway(req)

Bases: cherrypy.wsgiserver.wsgiserver3.Gateway

A base class to interface HTTPServer with WSGI.

get_environ()

Return a new environ dict targeting the given wsgi.version

respond()

Process the current request.

start_response(status, headers, exc_info=None)

WSGI callable to begin the HTTP response.

write(chunk)

WSGI callable to write unbuffered data to the client.

This method is also used internally by start_response (to write data from the iterable returned by the WSGI application).

class cherrypy.wsgiserver.wsgiserver3.WSGIGateway_10(req)

Bases: cherrypy.wsgiserver.wsgiserver3.WSGIGateway

A Gateway class to interface HTTPServer with WSGI 1.0.x.

get_environ()

Return a new environ dict targeting the given wsgi.version

class cherrypy.wsgiserver.wsgiserver3.WSGIGateway_u0(req)

Bases: cherrypy.wsgiserver.wsgiserver3.WSGIGateway_10

A Gateway class to interface HTTPServer with WSGI u.0.

WSGI u.0 is an experimental protocol, which uses unicode for keys and values in both Python 2 and Python 3.

get_environ()

Return a new environ dict targeting the given wsgi.version

class cherrypy.wsgiserver.wsgiserver3.WSGIPathInfoDispatcher(apps)

Bases: object

A WSGI dispatcher for dispatch based on the PATH_INFO.

apps: a dict or list of (path_prefix, app) pairs.

cherrypy.wsgiserver.wsgiserver3.get_ssl_adapter_class(name='builtin')

Return an SSL adapter class for the given name.

Module contents

class cherrypy.wsgiserver.HTTPRequest(server, conn)

Bases: object

An HTTP Request (and response).

A single HTTP connection may consist of multiple request/response pairs.

chunked_write = False
close_connection = False
conn = None
inheaders = {}
outheaders = []
parse_request()

Parse the next HTTP request start-line and message-headers.

parse_request_uri(uri)

Parse a Request-URI into (scheme, authority, path).

Note that Request-URI’s must be one of:

Request-URI    = "*" | absoluteURI | abs_path | authority

Therefore, a Request-URI which starts with a double forward-slash cannot be a “net_path”:

net_path      = "//" authority [ abs_path ]

Instead, it must be interpreted as an “abs_path” with an empty first path segment:

abs_path      = "/"  path_segments
path_segments = segment *( "/" segment )
segment       = *pchar *( ";" param )
param         = *pchar
read_request_headers()

Read self.rfile into self.inheaders. Return success.

read_request_line()
ready = False
respond()

Call the gateway and write its iterable output.

send_headers()

Assert, process, and send the HTTP response message-headers.

You must set self.status, and self.outheaders before calling this.

server = None
simple_response(status, msg='')

Write a simple response back to the client.

write(chunk)

Write unbuffered data to the client.

class cherrypy.wsgiserver.HTTPConnection(server, sock, makefile=<class 'cherrypy.wsgiserver.wsgiserver2.CP_fileobject'>)

Bases: object

An HTTP connection (active socket).

server: the Server object which received this connection. socket: the raw socket object (usually TCP) for this connection. makefile: a fileobject class for reading from the socket.

RequestHandlerClass

alias of HTTPRequest

close()

Close the socket underlying this connection.

communicate()

Read each request and respond appropriately.

linger = False
rbufsize = -1
remote_addr = None
remote_port = None
ssl_env = None
wbufsize = -1
class cherrypy.wsgiserver.HTTPServer(bind_addr, gateway, minthreads=10, maxthreads=-1, server_name=None)

Bases: object

An HTTP server.

ConnectionClass

alias of HTTPConnection

bind(family, type, proto=0)

Create (or recreate) the actual socket object.

bind_addr

The interface on which to listen for connections.

For TCP sockets, a (host, port) tuple. Host values may be any IPv4 or IPv6 address, or any valid hostname. The string ‘localhost’ is a synonym for ‘127.0.0.1’ (or ‘::1’, if your hosts file prefers IPv6). The string ‘0.0.0.0’ is a special IPv4 entry meaning “any active interface” (INADDR_ANY), and ‘::’ is the similar IN6ADDR_ANY for IPv6. The empty string or None are not allowed.

For UNIX sockets, supply the filename as a string.

clear_stats()
error_log(msg='', level=20, traceback=False)
gateway = None
interrupt

Set this to an Exception instance to interrupt the server.

max_request_body_size = 0
max_request_header_size = 0
maxthreads = None
minthreads = None
nodelay = True
protocol = 'HTTP/1.1'
ready = False
request_queue_size = 5
runtime()
server_name = None
shutdown_timeout = 5
software = None
ssl_adapter = None
start()

Run the server forever.

stop()

Gracefully shutdown a server that is serving forever.

tick()

Accept a new connection and put it on the Queue.

timeout = 10
version = 'CherryPy/3.3.0'
class cherrypy.wsgiserver.SizeCheckWrapper(rfile, maxlen)

Bases: object

Wraps a file-like object, raising MaxSizeExceeded if too large.

close()
next()
read(size=None)
readline(size=None)
readlines(sizehint=0)
class cherrypy.wsgiserver.KnownLengthRFile(rfile, content_length)

Bases: object

Wraps a file-like object, returning an empty string when exhausted.

close()
read(size=None)
readline(size=None)
readlines(sizehint=0)
class cherrypy.wsgiserver.ChunkedRFile(rfile, maxlen, bufsize=8192)

Bases: object

Wraps a file-like object, returning an empty string when exhausted.

This class is intended to provide a conforming wsgi.input value for request entities that have been encoded with the ‘chunked’ transfer encoding.

close()
read(size=None)
read_trailer_lines()
readline(size=None)
readlines(sizehint=0)
exception cherrypy.wsgiserver.MaxSizeExceeded

Bases: exceptions.Exception

exception cherrypy.wsgiserver.NoSSLError

Bases: exceptions.Exception

Exception raised when a client speaks HTTP to an HTTPS socket.

exception cherrypy.wsgiserver.FatalSSLAlert

Bases: exceptions.Exception

Exception raised when the SSL implementation signals a fatal alert.

class cherrypy.wsgiserver.WorkerThread(server)

Bases: threading.Thread

Thread which continuously polls a Queue for Connection objects.

Due to the timing issues of polling a Queue, a WorkerThread does not check its own ‘ready’ flag after it has started. To stop the thread, it is necessary to stick a _SHUTDOWNREQUEST object onto the Queue (one for each running WorkerThread).

conn = None
ready = False
run()
server = None
class cherrypy.wsgiserver.ThreadPool(server, min=10, max=-1)

Bases: object

A Request Queue for an HTTPServer which pools threads.

ThreadPool objects must provide min, get(), put(obj), start() and stop(timeout) attributes.

grow(amount)

Spawn new worker threads (not above self.max).

idle

Number of worker threads which are idle. Read-only.

put(obj)
qsize
shrink(amount)

Kill off worker threads (not below self.min).

start()

Start the pool of threads.

stop(timeout=5)
class cherrypy.wsgiserver.SSLAdapter(certificate, private_key, certificate_chain=None)

Bases: object

Base class for SSL driver library adapters.

Required methods:

  • wrap(sock) -> (wrapped socket, ssl environ dict)
  • makefile(sock, mode='r', bufsize=DEFAULT_BUFFER_SIZE) -> socket file object
makefile(sock, mode='r', bufsize=-1)
wrap(sock)
class cherrypy.wsgiserver.CherryPyWSGIServer(bind_addr, wsgi_app, numthreads=10, server_name=None, max=-1, request_queue_size=5, timeout=10, shutdown_timeout=5)

Bases: cherrypy.wsgiserver.wsgiserver2.HTTPServer

A subclass of HTTPServer which calls a WSGI application.

numthreads
wsgi_version = (1, 0)
class cherrypy.wsgiserver.Gateway(req)

Bases: object

A base class to interface HTTPServer with other systems, such as WSGI.

respond()

Process the current request. Must be overridden in a subclass.

class cherrypy.wsgiserver.WSGIGateway(req)

Bases: cherrypy.wsgiserver.wsgiserver2.Gateway

A base class to interface HTTPServer with WSGI.

get_environ()

Return a new environ dict targeting the given wsgi.version

respond()

Process the current request.

start_response(status, headers, exc_info=None)

WSGI callable to begin the HTTP response.

write(chunk)

WSGI callable to write unbuffered data to the client.

This method is also used internally by start_response (to write data from the iterable returned by the WSGI application).

class cherrypy.wsgiserver.WSGIGateway_10(req)

Bases: cherrypy.wsgiserver.wsgiserver2.WSGIGateway

A Gateway class to interface HTTPServer with WSGI 1.0.x.

get_environ()

Return a new environ dict targeting the given wsgi.version

class cherrypy.wsgiserver.WSGIGateway_u0(req)

Bases: cherrypy.wsgiserver.wsgiserver2.WSGIGateway_10

A Gateway class to interface HTTPServer with WSGI u.0.

WSGI u.0 is an experimental protocol, which uses unicode for keys and values in both Python 2 and Python 3.

get_environ()

Return a new environ dict targeting the given wsgi.version

class cherrypy.wsgiserver.WSGIPathInfoDispatcher(apps)

Bases: object

A WSGI dispatcher for dispatch based on the PATH_INFO.

apps: a dict or list of (path_prefix, app) pairs.

cherrypy.wsgiserver.get_ssl_adapter_class(name='pyopenssl')

Return an SSL adapter class for the given name.