cherrypy package

Subpackages

Submodules

cherrypy._cpchecker module

class cherrypy._cpchecker.Checker

Bases: object

A checker for CherryPy sites and their mounted applications.

When this object is called at engine startup, it executes each of its own methods whose names start with check_. If you wish to disable selected checks, simply add a line in your global config which sets the appropriate method to False:

[global]
checker.check_skipped_app_config = False

You may also dynamically add or replace check_* methods in this way.

check_app_config_brackets()

Check for Application config with extraneous brackets in section names.

check_app_config_entries_dont_start_with_script_name()

Check for Application config with sections that repeat script_name.

check_compatibility()

Process config and warn on each obsolete or deprecated entry.

check_config_namespaces()

Process config and warn on each unknown config namespace.

check_config_types()

Assert that config values are of the same type as default values.

check_localhost()

Warn if any socket_host is ‘localhost’. See #711.

check_site_config_entries_in_app_config()

Check for mounted Applications that have site-scoped config.

check_skipped_app_config()

Check for mounted Applications that have no config.

check_static_paths()

Check Application config for incorrect static paths.

deprecated = {}
extra_config_namespaces = []
formatwarning(message, category, filename, lineno, line=None)

Function to format a warning.

global_config_contained_paths = False
known_config_types = {'engine.__doc__': <type 'str'>, 'engine.__dict__': <type 'dict'>, 'request.show_tracebacks': <type 'bool'>, 'request.params': <type 'dict'>, 'log.screen': <type 'bool'>, 'engine.listeners': <type 'dict'>, 'log.access_file': <type 'str'>, 'request.server_protocol': <type 'str'>, 'log.access_log_format': <type 'str'>, 'server.max_request_body_size': <type 'int'>, 'server.shutdown_timeout': <type 'int'>, 'server.socket_port': <type 'int'>, 'request.__class__': <type 'type'>, 'response.__attrname__': <type 'str'>, 'log.wsgi': <type 'bool'>, 'request.protocol': <type 'tuple'>, 'response.__dict__': <type 'dict'>, 'request.error_page': <type 'dict'>, 'response.time': <type 'float'>, 'response.stream': <type 'bool'>, 'server._socket_host': <type 'str'>, 'engine.max_cloexec_files': <type 'int'>, 'response.timeout': <type 'int'>, 'server.__doc__': <type 'str'>, 'response._body': <type 'list'>, 'request.script_name': <type 'str'>, 'request.scheme': <type 'str'>, 'request.closed': <type 'bool'>, 'server.protocol_version': <type 'str'>, 'server.max_request_header_size': <type 'int'>, 'request.throws': <type 'tuple'>, 'request.request_line': <type 'str'>, 'log.__dict__': <type 'dict'>, 'server.thread_pool_max': <type 'int'>, 'engine._priorities': <type 'dict'>, 'request.__dict__': <type 'dict'>, 'request.method': <type 'str'>, 'request.__slots__': <type 'list'>, 'request.header_list': <type 'list'>, 'request.toolmaps': <type 'dict'>, 'request.methods_with_bodies': <type 'tuple'>, 'request.process_request_body': <type 'bool'>, 'request.base': <type 'str'>, 'server.ssl_module': <type 'str'>, 'server.__module__': <type 'str'>, 'server.wsgi_version': <type 'tuple'>, 'log.__module__': <type 'str'>, 'server.running': <type 'bool'>, 'log.__doc__': <type 'str'>, 'server.bind_addr': <type 'tuple'>, 'server.__class__': <type 'type'>, 'server.__dict__': <type 'dict'>, 'log.__class__': <type 'type'>, 'server.nodelay': <type 'bool'>, 'engine.__class__': <type 'type'>, 'response.__class__': <type 'type'>, 'engine.__module__': <type 'str'>, 'response.body': <type 'list'>, 'request.__module__': <type 'str'>, 'server.socket_timeout': <type 'int'>, 'server.thread_pool': <type 'int'>, 'response.timed_out': <type 'bool'>, 'response.__slots__': <type 'list'>, 'request.query_string': <type 'str'>, 'log.logger_root': <type 'str'>, 'log.error_file': <type 'str'>, 'request.query_string_encoding': <type 'str'>, 'server.socket_host': <type 'str'>, 'engine.execv': <type 'bool'>, 'request.throw_errors': <type 'bool'>, 'request.show_mismatched_params': <type 'bool'>, 'request.__attrname__': <type 'str'>, 'request.path_info': <type 'str'>, 'server.socket_queue_size': <type 'int'>, 'response.__module__': <type 'str'>, 'server.statistics': <type 'bool'>}
obsolete = {'log_request_headers': 'tools.log_headers.on', 'log_config_options': None, 'throw_errors': 'request.throw_errors', 'log_to_screen': 'log.screen', 'log_file_not_found': None, 'log_access_file': 'log.access_file', 'show_tracebacks': 'request.show_tracebacks', 'log_file': 'log.error_file', 'server.default_content_type': 'tools.response_headers.headers', 'profiler.on': 'cherrypy.tree.mount(profiler.make_app(cherrypy.Application(Root())))'}
on = True

If True (the default), run all checks; if False, turn off all checks.

cherrypy._cpcompat module

Compatibility code for using CherryPy with various versions of Python.

CherryPy 3.2 is compatible with Python versions 2.3+. This module provides a useful abstraction over the differences between Python versions, sometimes by preferring a newer idiom, sometimes an older one, and sometimes a custom one.

In particular, Python 2 uses str and ‘’ for byte strings, while Python 3 uses str and ‘’ for unicode strings. We will call each of these the ‘native string’ type for each version. Because of this major difference, this module provides new ‘bytestr’, ‘unicodestr’, and ‘nativestr’ attributes, as well as two functions: ‘ntob’, which translates native strings (of type ‘str’) into byte strings regardless of Python version, and ‘ntou’, which translates native strings to unicode strings. This also provides a ‘BytesIO’ name for dealing specifically with bytes, and a ‘StringIO’ name for dealing with native strings. It also provides a ‘base64_decode’ function with native strings as input and output.

cherrypy._cpcompat.HTTPDate(timeval=None)
class cherrypy._cpcompat.SetDaemonProperty
cherrypy._cpcompat.assert_native(n)
cherrypy._cpcompat.base64_decode(n, encoding='ISO-8859-1')

Return the native string base64-decoded (as a native string).

cherrypy._cpcompat.copyitems(d)
cherrypy._cpcompat.copykeys(d)
cherrypy._cpcompat.copyvalues(d)
cherrypy._cpcompat.get_daemon(t)
cherrypy._cpcompat.iteritems(d)
cherrypy._cpcompat.iterkeys(d)
cherrypy._cpcompat.itervalues(d)
cherrypy._cpcompat.ntob(n, encoding='ISO-8859-1')

Return the given native string as a byte string in the given encoding.

cherrypy._cpcompat.ntou(n, encoding='ISO-8859-1')

Return the given native string as a unicode string with the given encoding.

cherrypy._cpcompat.random20()
cherrypy._cpcompat.set_daemon(t, val)
cherrypy._cpcompat.tonative(n, encoding='ISO-8859-1')

Return the given string as a native string in the given encoding.

cherrypy._cpcompat.unquote_qs(atom, encoding, errors='strict')

cherrypy._cpcompat_subprocess module

subprocess - Subprocesses with accessible I/O streams

This module allows you to spawn processes, connect to their input/output/error pipes, and obtain their return codes. This module intends to replace several other, older modules and functions, like:

os.system os.spawn* os.popen* popen2.* commands.*

Information about how the subprocess module can be used to replace these modules and functions can be found below.

Using the subprocess module

This module defines one class called Popen:

class Popen(args, bufsize=0, executable=None,
stdin=None, stdout=None, stderr=None, preexec_fn=None, close_fds=False, shell=False, cwd=None, env=None, universal_newlines=False, startupinfo=None, creationflags=0):

Arguments are:

args should be a string, or a sequence of program arguments. The program to execute is normally the first item in the args sequence or string, but can be explicitly set by using the executable argument.

On UNIX, with shell=False (default): In this case, the Popen class uses os.execvp() to execute the child program. args should normally be a sequence. A string will be treated as a sequence with the string as the only item (the program to execute).

On UNIX, with shell=True: If args is a string, it specifies the command string to execute through the shell. If args is a sequence, the first item specifies the command string, and any additional items will be treated as additional shell arguments.

On Windows: the Popen class uses CreateProcess() to execute the child program, which operates on strings. If args is a sequence, it will be converted to a string using the list2cmdline method. Please note that not all MS Windows applications interpret the command line the same way: The list2cmdline is designed for applications using the same rules as the MS C runtime.

bufsize, if given, has the same meaning as the corresponding argument to the built-in open() function: 0 means unbuffered, 1 means line buffered, any other positive value means use a buffer of (approximately) that size. A negative bufsize means to use the system default, which usually means fully buffered. The default value for bufsize is 0 (unbuffered).

stdin, stdout and stderr specify the executed programs’ standard input, standard output and standard error file handles, respectively. Valid values are PIPE, an existing file descriptor (a positive integer), an existing file object, and None. PIPE indicates that a new pipe to the child should be created. With None, no redirection will occur; the child’s file handles will be inherited from the parent. Additionally, stderr can be STDOUT, which indicates that the stderr data from the applications should be captured into the same file handle as for stdout.

If preexec_fn is set to a callable object, this object will be called in the child process just before the child is executed.

If close_fds is true, all file descriptors except 0, 1 and 2 will be closed before the child process is executed.

if shell is true, the specified command will be executed through the shell.

If cwd is not None, the current directory will be changed to cwd before the child is executed.

If env is not None, it defines the environment variables for the new process.

If universal_newlines is true, the file objects stdout and stderr are opened as a text files, but lines may be terminated by any of ‘n’, the Unix end-of-line convention, ‘r’, the Macintosh convention or ‘rn’, the Windows convention. All of these external representations are seen as ‘n’ by the Python program. Note: This feature is only available if Python is built with universal newline support (the default). Also, the newlines attribute of the file objects stdout, stdin and stderr are not updated by the communicate() method.

The startupinfo and creationflags, if given, will be passed to the underlying CreateProcess() function. They can specify things such as appearance of the main window and priority for the new process. (Windows only)

This module also defines some shortcut functions:

call(*popenargs, **kwargs):

Run command with arguments. Wait for command to complete, then return the returncode attribute.

The arguments are the same as for the Popen constructor. Example:

retcode = call([“ls”, “-l”])

check_call(*popenargs, **kwargs):

Run command with arguments. Wait for command to complete. If the exit code was zero then return, otherwise raise CalledProcessError. The CalledProcessError object will have the return code in the returncode attribute.

The arguments are the same as for the Popen constructor. Example:

check_call([“ls”, “-l”])

check_output(*popenargs, **kwargs):

Run command with arguments and return its output as a byte string.

If the exit code was non-zero it raises a CalledProcessError. The CalledProcessError object will have the return code in the returncode attribute and output in the output attribute.

The arguments are the same as for the Popen constructor. Example:

output = check_output([“ls”, “-l”, “/dev/null”])

Exceptions

Exceptions raised in the child process, before the new program has started to execute, will be re-raised in the parent. Additionally, the exception object will have one extra attribute called ‘child_traceback’, which is a string containing traceback information from the childs point of view.

The most common exception raised is OSError. This occurs, for example, when trying to execute a non-existent file. Applications should prepare for OSErrors.

A ValueError will be raised if Popen is called with invalid arguments.

check_call() and check_output() will raise CalledProcessError, if the called process returns a non-zero return code.

Security

Unlike some other popen functions, this implementation will never call /bin/sh implicitly. This means that all characters, including shell metacharacters, can safely be passed to child processes.

Popen objects

Instances of the Popen class have the following methods:

poll()
Check if child process has terminated. Returns returncode attribute.
wait()
Wait for child process to terminate. Returns returncode attribute.
communicate(input=None)

Interact with process: Send data to stdin. Read data from stdout and stderr, until end-of-file is reached. Wait for process to terminate. The optional input argument should be a string to be sent to the child process, or None, if no data should be sent to the child.

communicate() returns a tuple (stdout, stderr).

Note: The data read is buffered in memory, so do not use this method if the data size is large or unlimited.

The following attributes are also available:

stdin
If the stdin argument is PIPE, this attribute is a file object that provides input to the child process. Otherwise, it is None.
stdout
If the stdout argument is PIPE, this attribute is a file object that provides output from the child process. Otherwise, it is None.
stderr
If the stderr argument is PIPE, this attribute is file object that provides error output from the child process. Otherwise, it is None.
pid
The process ID of the child process.
returncode
The child return code. A None value indicates that the process hasn’t terminated yet. A negative value -N indicates that the child was terminated by signal N (UNIX only).

Replacing older functions with the subprocess module

In this section, “a ==> b” means that b can be used as a replacement for a.

Note: All functions in this section fail (more or less) silently if the executed program cannot be found; this module raises an OSError exception.

In the following examples, we assume that the subprocess module is imported with “from subprocess import *”.

Replacing /bin/sh shell backquote

output=`mycmd myarg` ==> output = Popen([“mycmd”, “myarg”], stdout=PIPE).communicate()[0]

Replacing shell pipe line

output=`dmesg | grep hda` ==> p1 = Popen([“dmesg”], stdout=PIPE) p2 = Popen([“grep”, “hda”], stdin=p1.stdout, stdout=PIPE) output = p2.communicate()[0]

Replacing os.system()

sts = os.system(“mycmd” + ” myarg”) ==> p = Popen(“mycmd” + ” myarg”, shell=True) pid, sts = os.waitpid(p.pid, 0)

Note:

  • Calling the program through the shell is usually not required.
  • It’s easier to look at the returncode attribute than the exitstatus.

A more real-world example would look like this:

try:

retcode = call(“mycmd” + ” myarg”, shell=True) if retcode < 0:

print >>sys.stderr, “Child was terminated by signal”, -retcode
else:
print >>sys.stderr, “Child returned”, retcode
except OSError, e:
print >>sys.stderr, “Execution failed:”, e

Replacing os.spawn*

P_NOWAIT example:

pid = os.spawnlp(os.P_NOWAIT, “/bin/mycmd”, “mycmd”, “myarg”) ==> pid = Popen([“/bin/mycmd”, “myarg”]).pid

P_WAIT example:

retcode = os.spawnlp(os.P_WAIT, “/bin/mycmd”, “mycmd”, “myarg”) ==> retcode = call([“/bin/mycmd”, “myarg”])

Vector example:

os.spawnvp(os.P_NOWAIT, path, args) ==> Popen([path] + args[1:])

Environment example:

os.spawnlpe(os.P_NOWAIT, “/bin/mycmd”, “mycmd”, “myarg”, env) ==> Popen([“/bin/mycmd”, “myarg”], env={“PATH”: “/usr/bin”})

Replacing os.popen*

pipe = os.popen(“cmd”, mode=’r’, bufsize) ==> pipe = Popen(“cmd”, shell=True, bufsize=bufsize, stdout=PIPE).stdout

pipe = os.popen(“cmd”, mode=’w’, bufsize) ==> pipe = Popen(“cmd”, shell=True, bufsize=bufsize, stdin=PIPE).stdin

(child_stdin, child_stdout) = os.popen2(“cmd”, mode, bufsize) ==> p = Popen(“cmd”, shell=True, bufsize=bufsize,

stdin=PIPE, stdout=PIPE, close_fds=True)

(child_stdin, child_stdout) = (p.stdin, p.stdout)

(child_stdin,
child_stdout, child_stderr) = os.popen3(“cmd”, mode, bufsize)

==> p = Popen(“cmd”, shell=True, bufsize=bufsize,

stdin=PIPE, stdout=PIPE, stderr=PIPE, close_fds=True)
(child_stdin,
child_stdout, child_stderr) = (p.stdin, p.stdout, p.stderr)
(child_stdin, child_stdout_and_stderr) = os.popen4(“cmd”, mode,
bufsize)

==> p = Popen(“cmd”, shell=True, bufsize=bufsize,

stdin=PIPE, stdout=PIPE, stderr=STDOUT, close_fds=True)

(child_stdin, child_stdout_and_stderr) = (p.stdin, p.stdout)

On Unix, os.popen2, os.popen3 and os.popen4 also accept a sequence as the command to execute, in which case arguments will be passed directly to the program without shell intervention. This usage can be replaced as follows:

(child_stdin, child_stdout) = os.popen2([“/bin/ls”, “-l”], mode,
bufsize)

==> p = Popen([“/bin/ls”, “-l”], bufsize=bufsize, stdin=PIPE, stdout=PIPE) (child_stdin, child_stdout) = (p.stdin, p.stdout)

Return code handling translates as follows:

pipe = os.popen(“cmd”, ‘w’) ... rc = pipe.close() if rc is not None and rc % 256:

print “There were some errors”

==> process = Popen(“cmd”, ‘w’, shell=True, stdin=PIPE) ... process.stdin.close() if process.wait() != 0:

print “There were some errors”

Replacing popen2.*

(child_stdout, child_stdin) = popen2.popen2(“somestring”, bufsize, mode) ==> p = Popen([“somestring”], shell=True, bufsize=bufsize

stdin=PIPE, stdout=PIPE, close_fds=True)

(child_stdout, child_stdin) = (p.stdout, p.stdin)

On Unix, popen2 also accepts a sequence as the command to execute, in which case arguments will be passed directly to the program without shell intervention. This usage can be replaced as follows:

(child_stdout, child_stdin) = popen2.popen2([“mycmd”, “myarg”], bufsize,
mode)

==> p = Popen([“mycmd”, “myarg”], bufsize=bufsize,

stdin=PIPE, stdout=PIPE, close_fds=True)

(child_stdout, child_stdin) = (p.stdout, p.stdin)

The popen2.Popen3 and popen2.Popen4 basically works as subprocess.Popen, except that:

  • subprocess.Popen raises an exception if the execution fails
  • the capturestderr argument is replaced with the stderr argument.
  • stdin=PIPE and stdout=PIPE must be specified.
  • popen2 closes all filedescriptors by default, but you have to specify close_fds=True with subprocess.Popen.
class cherrypy._cpcompat_subprocess.Popen(args, bufsize=0, executable=None, stdin=None, stdout=None, stderr=None, preexec_fn=None, close_fds=False, shell=False, cwd=None, env=None, universal_newlines=False, startupinfo=None, creationflags=0)

Bases: object

communicate(input=None)

Interact with process: Send data to stdin. Read data from stdout and stderr, until end-of-file is reached. Wait for process to terminate. The optional input argument should be a string to be sent to the child process, or None, if no data should be sent to the child.

communicate() returns a tuple (stdout, stderr).

kill()

Kill the process with SIGKILL

pipe_cloexec()

Create a pipe with FDs set CLOEXEC.

poll()
send_signal(sig)

Send a signal to the process

terminate()

Terminate the process with SIGTERM

wait()

Wait for child process to terminate. Returns returncode attribute.

cherrypy._cpcompat_subprocess.call(*popenargs, **kwargs)

Run command with arguments. Wait for command to complete, then return the returncode attribute.

The arguments are the same as for the Popen constructor. Example:

retcode = call([“ls”, “-l”])

cherrypy._cpcompat_subprocess.check_call(*popenargs, **kwargs)

Run command with arguments. Wait for command to complete. If the exit code was zero then return, otherwise raise CalledProcessError. The CalledProcessError object will have the return code in the returncode attribute.

The arguments are the same as for the Popen constructor. Example:

check_call([“ls”, “-l”])

cherrypy._cpcompat_subprocess.check_output(*popenargs, **kwargs)

Run command with arguments and return its output as a byte string.

If the exit code was non-zero it raises a CalledProcessError. The CalledProcessError object will have the return code in the returncode attribute and output in the output attribute.

The arguments are the same as for the Popen constructor. Example:

>>> check_output(["ls", "-l", "/dev/null"])
'crw-rw-rw- 1 root root 1, 3 Oct 18  2007 /dev/null\n'

The stdout argument is not allowed as it is used internally. To capture standard error in the result, use stderr=STDOUT.

>>> check_output(["/bin/sh", "-c",
...               "ls -l non_existent_file ; exit 0"],
...              stderr=STDOUT)
'ls: non_existent_file: No such file or directory\n'
exception cherrypy._cpcompat_subprocess.CalledProcessError(returncode, cmd, output=None)

Bases: exceptions.Exception

This exception is raised when a process run by check_call() or check_output() returns a non-zero exit status. The exit status will be stored in the returncode attribute; check_output() will also store the output in the output attribute.

cherrypy._cpconfig module

Configuration system for CherryPy.

Configuration in CherryPy is implemented via dictionaries. Keys are strings which name the mapped value, which may be of any type.

Architecture

CherryPy Requests are part of an Application, which runs in a global context, and configuration data may apply to any of those three scopes:

Global
Configuration entries which apply everywhere are stored in cherrypy.config.
Application
Entries which apply to each mounted application are stored on the Application object itself, as ‘app.config’. This is a two-level dict where each key is a path, or “relative URL” (for example, “/” or “/path/to/my/page”), and each value is a config dict. Usually, this data is provided in the call to tree.mount(root(), config=conf), although you may also use app.merge(conf).
Request
Each Request object possesses a single ‘Request.config’ dict. Early in the request process, this dict is populated by merging global config entries, Application entries (whose path equals or is a parent of Request.path_info), and any config acquired while looking up the page handler (see next).

Declaration

Configuration data may be supplied as a Python dictionary, as a filename, or as an open file object. When you supply a filename or file, CherryPy uses Python’s builtin ConfigParser; you declare Application config by writing each path as a section header:

[/path/to/my/page]
request.stream = True

To declare global configuration entries, place them in a [global] section.

You may also declare config entries directly on the classes and methods (page handlers) that make up your CherryPy application via the _cp_config attribute. For example:

class Demo:
    _cp_config = {'tools.gzip.on': True}

    def index(self):
        return "Hello world"
    index.exposed = True
    index._cp_config = {'request.show_tracebacks': False}

Note

This behavior is only guaranteed for the default dispatcher. Other dispatchers may have different restrictions on where you can attach _cp_config attributes.

Namespaces

Configuration keys are separated into namespaces by the first ”.” in the key. Current namespaces:

engine
Controls the ‘application engine’, including autoreload. These can only be declared in the global config.
tree
Grafts cherrypy.Application objects onto cherrypy.tree. These can only be declared in the global config.
hooks
Declares additional request-processing functions.
log
Configures the logging for each application. These can only be declared in the global or / config.
request
Adds attributes to each Request.
response
Adds attributes to each Response.
server
Controls the default HTTP server via cherrypy.server. These can only be declared in the global config.
tools
Runs and configures additional request-processing packages.
wsgi
Adds WSGI middleware to an Application’s “pipeline”. These can only be declared in the app’s root config (“/”).
checker
Controls the ‘checker’, which looks for common errors in app state (including config) when the engine starts. Global config only.

The only key that does not exist in a namespace is the “environment” entry. This special entry ‘imports’ other config entries from a template stored in cherrypy._cpconfig.environments[environment]. It only applies to the global config, and only when you use cherrypy.config.update.

You can define your own namespaces to be called at the Global, Application, or Request level, by adding a named handler to cherrypy.config.namespaces, app.namespaces, or app.request_class.namespaces. The name can be any string, and the handler must be either a callable or a (Python 2.5 style) context manager.

class cherrypy._cpconfig.Config(file=None, **kwargs)

Bases: cherrypy.lib.reprconf.Config

The ‘global’ configuration data for the entire CherryPy process.

environments = {'production': {'engine.autoreload.on': False, 'request.show_tracebacks': False, 'log.screen': False, 'request.show_mismatched_params': False, 'checker.on': False, 'tools.log_headers.on': False}, 'staging': {'checker.on': False, 'request.show_mismatched_params': False, 'engine.autoreload.on': False, 'request.show_tracebacks': False, 'tools.log_headers.on': False}, 'embedded': {'checker.on': False, 'engine.SIGTERM': None, 'engine.autoreload.on': False, 'request.show_tracebacks': False, 'request.show_mismatched_params': False, 'tools.log_headers.on': False, 'log.screen': False, 'engine.SIGHUP': None}, 'test_suite': {'engine.autoreload.on': False, 'request.show_tracebacks': True, 'log.screen': False, 'request.show_mismatched_params': True, 'checker.on': False, 'tools.log_headers.on': False}}
update(config)

Update self from a dict, file or filename.

cherrypy._cpconfig.merge(base, other)

Merge one app config (from a dict, file, or filename) into another.

If the given config is a filename, it will be appended to the list of files to monitor for “autoreload” changes.

cherrypy._cpdispatch module

CherryPy dispatchers.

A ‘dispatcher’ is the object which looks up the ‘page handler’ callable and collects config for the current request based on the path_info, other request attributes, and the application architecture. The core calls the dispatcher as early as possible, passing it a ‘path_info’ argument.

The default dispatcher discovers the page handler by matching path_info to a hierarchical arrangement of objects, starting at request.app.root.

class cherrypy._cpdispatch.Dispatcher(dispatch_method_name=None, translate='x00x01x02x03x04x05x06x07x08tnx0bx0crx0ex0fx10x11x12x13x14x15x16x17x18x19x1ax1bx1cx1dx1ex1f _______________0123456789_______ABCDEFGHIJKLMNOPQRSTUVWXYZ______abcdefghijklmnopqrstuvwxyz____x7fx80x81x82x83x84x85x86x87x88x89x8ax8bx8cx8dx8ex8fx90x91x92x93x94x95x96x97x98x99x9ax9bx9cx9dx9ex9fxa0xa1xa2xa3xa4xa5xa6xa7xa8xa9xaaxabxacxadxaexafxb0xb1xb2xb3xb4xb5xb6xb7xb8xb9xbaxbbxbcxbdxbexbfxc0xc1xc2xc3xc4xc5xc6xc7xc8xc9xcaxcbxccxcdxcexcfxd0xd1xd2xd3xd4xd5xd6xd7xd8xd9xdaxdbxdcxddxdexdfxe0xe1xe2xe3xe4xe5xe6xe7xe8xe9xeaxebxecxedxeexefxf0xf1xf2xf3xf4xf5xf6xf7xf8xf9xfaxfbxfcxfdxfexff')

Bases: object

CherryPy Dispatcher which walks a tree of objects to find a handler.

The tree is rooted at cherrypy.request.app.root, and each hierarchical component in the path_info argument is matched to a corresponding nested attribute of the root object. Matching handlers must have an ‘exposed’ attribute which evaluates to True. The special method name “index” matches a URI which ends in a slash (“/”). The special method name “default” may match a portion of the path_info (but only when no longer substring of the path_info matches some other object).

This is the default, built-in dispatcher for CherryPy.

dispatch_method_name = '_cp_dispatch'

The name of the dispatch method that nodes may optionally implement to provide their own dynamic dispatch algorithm.

find_handler(path)

Return the appropriate page handler, plus any virtual path.

This will return two objects. The first will be a callable, which can be used to generate page output. Any parameters from the query string or request body will be sent to that callable as keyword arguments.

The callable is found by traversing the application’s tree, starting from cherrypy.request.app.root, and matching path components to successive objects in the tree. For example, the URL “/path/to/handler” might return root.path.to.handler.

The second object returned will be a list of names which are ‘virtual path’ components: parts of the URL which are dynamic, and were not used when looking up the handler. These virtual path components are passed to the handler as positional arguments.

class cherrypy._cpdispatch.LateParamPageHandler(callable, *args, **kwargs)

Bases: cherrypy._cpdispatch.PageHandler

When passing cherrypy.request.params to the page handler, we do not want to capture that dict too early; we want to give tools like the decoding tool a chance to modify the params dict in-between the lookup of the handler and the actual calling of the handler. This subclass takes that into account, and allows request.params to be ‘bound late’ (it’s more complicated than that, but that’s the effect).

kwargs

page handler kwargs (with cherrypy.request.params copied in)

class cherrypy._cpdispatch.MethodDispatcher(dispatch_method_name=None, translate='x00x01x02x03x04x05x06x07x08tnx0bx0crx0ex0fx10x11x12x13x14x15x16x17x18x19x1ax1bx1cx1dx1ex1f _______________0123456789_______ABCDEFGHIJKLMNOPQRSTUVWXYZ______abcdefghijklmnopqrstuvwxyz____x7fx80x81x82x83x84x85x86x87x88x89x8ax8bx8cx8dx8ex8fx90x91x92x93x94x95x96x97x98x99x9ax9bx9cx9dx9ex9fxa0xa1xa2xa3xa4xa5xa6xa7xa8xa9xaaxabxacxadxaexafxb0xb1xb2xb3xb4xb5xb6xb7xb8xb9xbaxbbxbcxbdxbexbfxc0xc1xc2xc3xc4xc5xc6xc7xc8xc9xcaxcbxccxcdxcexcfxd0xd1xd2xd3xd4xd5xd6xd7xd8xd9xdaxdbxdcxddxdexdfxe0xe1xe2xe3xe4xe5xe6xe7xe8xe9xeaxebxecxedxeexefxf0xf1xf2xf3xf4xf5xf6xf7xf8xf9xfaxfbxfcxfdxfexff')

Bases: cherrypy._cpdispatch.Dispatcher

Additional dispatch based on cherrypy.request.method.upper().

Methods named GET, POST, etc will be called on an exposed class. The method names must be all caps; the appropriate Allow header will be output showing all capitalized method names as allowable HTTP verbs.

Note that the containing class must be exposed, not the methods.

class cherrypy._cpdispatch.PageHandler(callable, *args, **kwargs)

Bases: object

Callable which sets response.body.

args

The ordered args should be accessible from post dispatch hooks

get_args()
get_kwargs()
kwargs

The named kwargs should be accessible from post dispatch hooks

set_args(args)
set_kwargs(kwargs)
class cherrypy._cpdispatch.RoutesDispatcher(full_result=False, **mapper_options)

Bases: object

A Routes based dispatcher for CherryPy.

connect(name, route, controller, **kwargs)
find_handler(path_info)

Find the right page handler, and set request.config.

redirect(url)
cherrypy._cpdispatch.VirtualHost(next_dispatcher=<cherrypy._cpdispatch.Dispatcher object at 0x7f3628059a50>, use_x_forwarded_host=True, **domains)

Select a different handler based on the Host header.

This can be useful when running multiple sites within one CP server. It allows several domains to point to different parts of a single website structure. For example:

http://www.domain.example  ->  root
http://www.domain2.example  ->  root/domain2/
http://www.domain2.example:443  ->  root/secure

can be accomplished via the following config:

[/]
request.dispatch = cherrypy.dispatch.VirtualHost(
    **{'www.domain2.example': '/domain2',
       'www.domain2.example:443': '/secure',
      })
next_dispatcher
The next dispatcher object in the dispatch chain. The VirtualHost dispatcher adds a prefix to the URL and calls another dispatcher. Defaults to cherrypy.dispatch.Dispatcher().
use_x_forwarded_host
If True (the default), any “X-Forwarded-Host” request header will be used instead of the “Host” header. This is commonly added by HTTP servers (such as Apache) when proxying.
**domains
A dict of {host header value: virtual prefix} pairs. The incoming “Host” request header is looked up in this dict, and, if a match is found, the corresponding “virtual prefix” value will be prepended to the URL path before calling the next dispatcher. Note that you often need separate entries for “example.com” and “www.example.com”. In addition, “Host” headers may contain the port number.
cherrypy._cpdispatch.XMLRPCDispatcher(next_dispatcher=<cherrypy._cpdispatch.Dispatcher object at 0x7f362802c350>)
cherrypy._cpdispatch.test_callable_spec(callable, callable_args, callable_kwargs)

Inspect callable and test to see if the given args are suitable for it.

When an error occurs during the handler’s invoking stage there are 2 erroneous cases: 1. Too many parameters passed to a function which doesn’t define

one of *args or **kwargs.
  1. Too little parameters are passed to the function.

There are 3 sources of parameters to a cherrypy handler. 1. query string parameters are passed as keyword parameters to the

handler.
  1. body parameters are also passed as keyword parameters.
  2. when partial matching occurs, the final path atoms are passed as positional args.

Both the query string and path atoms are part of the URI. If they are incorrect, then a 404 Not Found should be raised. Conversely the body parameters are part of the request; if they are invalid a 400 Bad Request.

cherrypy._cpdispatch.validate_translator(t)

cherrypy._cperror module

Exception classes for CherryPy.

CherryPy provides (and uses) exceptions for declaring that the HTTP response should be a status other than the default “200 OK”. You can raise them like normal Python exceptions. You can also call them and they will raise themselves; this means you can set an HTTPError or HTTPRedirect as the request.handler.

Redirecting POST

When you GET a resource and are redirected by the server to another Location, there’s generally no problem since GET is both a “safe method” (there should be no side-effects) and an “idempotent method” (multiple calls are no different than a single call).

POST, however, is neither safe nor idempotent–if you charge a credit card, you don’t want to be charged twice by a redirect!

For this reason, none of the 3xx responses permit a user-agent (browser) to resubmit a POST on redirection without first confirming the action with the user:

300 Multiple Choices Confirm with the user
301 Moved Permanently Confirm with the user
302 Found (Object moved temporarily) Confirm with the user
303 See Other GET the new URI–no confirmation
304 Not modified (for conditional GET only–POST should not raise this error)
305 Use Proxy Confirm with the user
307 Temporary Redirect Confirm with the user

However, browsers have historically implemented these restrictions poorly; in particular, many browsers do not force the user to confirm 301, 302 or 307 when redirecting POST. For this reason, CherryPy defaults to 303, which most user-agents appear to have implemented correctly. Therefore, if you raise HTTPRedirect for a POST request, the user-agent will most likely attempt to GET the new URI (without asking for confirmation from the user). We realize this is confusing for developers, but it’s the safest thing we could do. You are of course free to raise HTTPRedirect(uri, status=302) or any other 3xx status if you know what you’re doing, but given the environment, we couldn’t let any of those be the default.

Custom Error Handling

refman/cperrors.gif

Anticipated HTTP responses

The ‘error_page’ config namespace can be used to provide custom HTML output for expected responses (like 404 Not Found). Supply a filename from which the output will be read. The contents will be interpolated with the values %(status)s, %(message)s, %(traceback)s, and %(version)s using plain old Python string formatting.

_cp_config = {
    'error_page.404': os.path.join(localDir, "static/index.html")
}

Beginning in version 3.1, you may also provide a function or other callable as an error_page entry. It will be passed the same status, message, traceback and version arguments that are interpolated into templates:

def error_page_402(status, message, traceback, version):
    return "Error %s - Well, I'm very sorry but you haven't paid!" % status
cherrypy.config.update({'error_page.402': error_page_402})

Also in 3.1, in addition to the numbered error codes, you may also supply “error_page.default” to handle all codes which do not have their own error_page entry.

Unanticipated errors

CherryPy also has a generic error handling mechanism: whenever an unanticipated error occurs in your code, it will call Request.error_response to set the response status, headers, and body. By default, this is the same output as HTTPError(500). If you want to provide some other behavior, you generally replace “request.error_response”.

Here is some sample code that shows how to display a custom error message and send an e-mail containing the error:

from cherrypy import _cperror

def handle_error():
    cherrypy.response.status = 500
    cherrypy.response.body = [
        "<html><body>Sorry, an error occured</body></html>"
    ]
    sendMail('error@domain.com',
             'Error in your web app',
             _cperror.format_exc())

class Root:
    _cp_config = {'request.error_response': handle_error}

Note that you have to explicitly set response.body and not simply return an error message as a result.

exception cherrypy._cperror.CherryPyException

Bases: exceptions.Exception

A base class for CherryPy exceptions.

exception cherrypy._cperror.HTTPError(status=500, message=None)

Bases: cherrypy._cperror.CherryPyException

Exception used to return an HTTP error code (4xx-5xx) to the client.

This exception can be used to automatically send a response using a http status code, with an appropriate error page. It takes an optional status argument (which must be between 400 and 599); it defaults to 500 (“Internal Server Error”). It also takes an optional message argument, which will be returned in the response body. See RFC2616 for a complete list of available error codes and when to use them.

Examples:

raise cherrypy.HTTPError(403)
raise cherrypy.HTTPError(
    "403 Forbidden", "You are not allowed to access this resource.")
code = None

The integer HTTP status code.

get_error_page(*args, **kwargs)
reason = None

The HTTP Reason-Phrase string.

set_response()

Modify cherrypy.response status, headers, and body to represent self.

CherryPy uses this internally, but you can also use it to create an HTTPError object and set its output without raising the exception.

status = None

The HTTP status code. May be of type int or str (with a Reason-Phrase).

exception cherrypy._cperror.HTTPRedirect(urls, status=None, encoding=None)

Bases: cherrypy._cperror.CherryPyException

Exception raised when the request should be redirected.

This exception will force a HTTP redirect to the URL or URL’s you give it. The new URL must be passed as the first argument to the Exception, e.g., HTTPRedirect(newUrl). Multiple URLs are allowed in a list. If a URL is absolute, it will be used as-is. If it is relative, it is assumed to be relative to the current cherrypy.request.path_info.

If one of the provided URL is a unicode object, it will be encoded using the default encoding or the one passed in parameter.

There are multiple types of redirect, from which you can select via the status argument. If you do not provide a status arg, it defaults to 303 (or 302 if responding with HTTP/1.0).

Examples:

raise cherrypy.HTTPRedirect("")
raise cherrypy.HTTPRedirect("/abs/path", 307)
raise cherrypy.HTTPRedirect(["path1", "path2?a=1&b=2"], 301)

See Redirecting POST for additional caveats.

encoding = 'utf-8'

The encoding when passed urls are not native strings

set_response()

Modify cherrypy.response status, headers, and body to represent self.

CherryPy uses this internally, but you can also use it to create an HTTPRedirect object and set its output without raising the exception.

status = None

The integer HTTP status code to emit.

urls = None

The list of URL’s to emit.

exception cherrypy._cperror.InternalRedirect(path, query_string='')

Bases: cherrypy._cperror.CherryPyException

Exception raised to switch to the handler for a different URL.

This exception will redirect processing to another path within the site (without informing the client). Provide the new path as an argument when raising the exception. Provide any params in the querystring for the new URL.

exception cherrypy._cperror.NotFound(path=None)

Bases: cherrypy._cperror.HTTPError

Exception raised when a URL could not be mapped to any handler (404).

This is equivalent to raising HTTPError("404 Not Found").

exception cherrypy._cperror.TimeoutError

Bases: cherrypy._cperror.CherryPyException

Exception raised when Response.timed_out is detected.

cherrypy._cperror.bare_error(extrabody=None)

Produce status, headers, body for a critical error.

Returns a triple without calling any other questionable functions, so it should be as error-free as possible. Call it from an HTTP server if you get errors outside of the request.

If extrabody is None, a friendly but rather unhelpful error message is set in the body. If extrabody is a string, it will be appended as-is to the body.

cherrypy._cperror.clean_headers(status)

Remove any headers which should not apply to an error response.

cherrypy._cperror.format_exc(exc=None)

Return exc (or sys.exc_info if None), formatted.

cherrypy._cperror.get_error_page(status, **kwargs)

Return an HTML page, containing a pretty error response.

status should be an int or a str. kwargs will be interpolated into the page template.

cherrypy._cplogging module

Simple config

Although CherryPy uses the Python logging module, it does so behind the scenes so that simple logging is simple, but complicated logging is still possible. “Simple” logging means that you can log to the screen (i.e. console/stdout) or to a file, and that you can easily have separate error and access log files.

Here are the simplified logging settings. You use these by adding lines to your config file or dict. You should set these at either the global level or per application (see next), but generally not both.

  • log.screen: Set this to True to have both “error” and “access” messages printed to stdout.
  • log.access_file: Set this to an absolute filename where you want “access” messages written.
  • log.error_file: Set this to an absolute filename where you want “error” messages written.

Many events are automatically logged; to log your own application events, call cherrypy.log().

Architecture

Separate scopes

CherryPy provides log managers at both the global and application layers. This means you can have one set of logging rules for your entire site, and another set of rules specific to each application. The global log manager is found at cherrypy.log(), and the log manager for each application is found at app.log. If you’re inside a request, the latter is reachable from cherrypy.request.app.log; if you’re outside a request, you’ll have to obtain a reference to the app: either the return value of tree.mount() or, if you used quickstart() instead, via cherrypy.tree.apps['/'].

By default, the global logs are named “cherrypy.error” and “cherrypy.access”, and the application logs are named “cherrypy.error.2378745” and “cherrypy.access.2378745” (the number is the id of the Application object). This means that the application logs “bubble up” to the site logs, so if your application has no log handlers, the site-level handlers will still log the messages.

Errors vs. Access

Each log manager handles both “access” messages (one per HTTP request) and “error” messages (everything else). Note that the “error” log is not just for errors! The format of access messages is highly formalized, but the error log isn’t–it receives messages from a variety of sources (including full error tracebacks, if enabled).

If you are logging the access log and error log to the same source, then there is a possibility that a specially crafted error message may replicate an access log message as described in CWE-117. In this case it is the application developer’s responsibility to manually escape data before using CherryPy’s log() functionality, or they may create an application that is vulnerable to CWE-117. This would be achieved by using a custom handler escape any special characters, and attached as described below.

Custom Handlers

The simple settings above work by manipulating Python’s standard logging module. So when you need something more complex, the full power of the standard module is yours to exploit. You can borrow or create custom handlers, formats, filters, and much more. Here’s an example that skips the standard FileHandler and uses a RotatingFileHandler instead:

#python
log = app.log

# Remove the default FileHandlers if present.
log.error_file = ""
log.access_file = ""

maxBytes = getattr(log, "rot_maxBytes", 10000000)
backupCount = getattr(log, "rot_backupCount", 1000)

# Make a new RotatingFileHandler for the error log.
fname = getattr(log, "rot_error_file", "error.log")
h = handlers.RotatingFileHandler(fname, 'a', maxBytes, backupCount)
h.setLevel(DEBUG)
h.setFormatter(_cplogging.logfmt)
log.error_log.addHandler(h)

# Make a new RotatingFileHandler for the access log.
fname = getattr(log, "rot_access_file", "access.log")
h = handlers.RotatingFileHandler(fname, 'a', maxBytes, backupCount)
h.setLevel(DEBUG)
h.setFormatter(_cplogging.logfmt)
log.access_log.addHandler(h)

The rot_* attributes are pulled straight from the application log object. Since “log.*” config entries simply set attributes on the log object, you can add custom attributes to your heart’s content. Note that these handlers are used ‘’instead’’ of the default, simple handlers outlined above (so don’t set the “log.error_file” config entry, for example).

class cherrypy._cplogging.LogManager(appid=None, logger_root='cherrypy')

Bases: object

An object to assist both simple and advanced logging.

cherrypy.log is an instance of this class.

access()

Write to the access log (in Apache/NCSA Combined Log format).

See the apache documentation for format details.

CherryPy calls this automatically for you. Note there are no arguments; it collects the data itself from cherrypy.request.

Like Apache started doing in 2.0.46, non-printable and other special characters in %r (and we expand that to all parts) are escaped using xhh sequences, where hh stands for the hexadecimal representation of the raw byte. Exceptions from this rule are ” and , which are escaped by prepending a backslash, and all whitespace characters, which are written in their C-style notation (n, t, etc).

access_file

The filename for self.access_log.

If you set this to a string, it’ll add the appropriate FileHandler for you. If you set it to None or '', it will remove the handler.

access_log = None

The actual logging.Logger instance for access messages.

access_log_format = '%(h)s %(l)s %(u)s %(t)s "%(r)s" %(s)s %(b)s "%(f)s" "%(a)s"'
appid = None

The id() of the Application object which owns this log manager. If this is a global log manager, appid is None.

error(msg='', context='', severity=20, traceback=False)

Write the given msg to the error log.

This is not just for errors! Applications may call this at any time to log application-specific information.

If traceback is True, the traceback of the current exception (if any) will be appended to msg.

error_file

The filename for self.error_log.

If you set this to a string, it’ll add the appropriate FileHandler for you. If you set it to None or '', it will remove the handler.

error_log = None

The actual logging.Logger instance for error messages.

logger_root = None

The “top-level” logger name.

This string will be used as the first segment in the Logger names. The default is “cherrypy”, for example, in which case the Logger names will be of the form:

cherrypy.error.<appid>
cherrypy.access.<appid>
reopen_files()

Close and reopen all file handlers.

screen

Turn stderr/stdout logging on or off.

If you set this to True, it’ll add the appropriate StreamHandler for you. If you set it to False, it will remove the handler.

time()

Return now() in Apache Common Log Format (no timezone).

wsgi

Write errors to wsgi.errors.

If you set this to True, it’ll add the appropriate WSGIErrorHandler for you (which writes errors to wsgi.errors). If you set it to False, it will remove the handler.

class cherrypy._cplogging.NullHandler(level=0)

Bases: logging.Handler

A no-op logging handler to silence the logging.lastResort handler.

createLock()
emit(record)
handle(record)
class cherrypy._cplogging.WSGIErrorHandler(level=0)

Bases: logging.Handler

A handler class which writes logging records to environ[‘wsgi.errors’].

emit(record)

Emit a record.

flush()

Flushes the stream.

cherrypy._cpmodpy module

Native adapter for serving CherryPy via mod_python

Basic usage:

# Application in a module called myapp.py

import cherrypy

class Root:

@cherrypy.expose def index(self):

return ‘Hi there, Ho there, Hey there’

# We will use this method from the mod_python configuration # as the entry point to our application def setup_server():

cherrypy.tree.mount(Root()) cherrypy.config.update({‘environment’: ‘production’,

‘log.screen’: False, ‘show_tracebacks’: False})

# or a file that will be loaded at # apache startup ##########################################

# Start DocumentRoot “/” Listen 8080 LoadModule python_module /usr/lib/apache2/modules/mod_python.so

<Location “/”>
PythonPath “sys.path+[‘/path/to/my/application’]” SetHandler python-program PythonHandler cherrypy._cpmodpy::handler PythonOption cherrypy.setup myapp::setup_server PythonDebug On

</Location> # End

The actual path to your mod_python.so is dependent on your environment. In this case we suppose a global mod_python installation on a Linux distribution such as Ubuntu.

We do set the PythonPath configuration setting so that your application can be found by from the user running the apache2 instance. Of course if your application resides in the global site-package this won’t be needed.

Then restart apache2 and access http://127.0.0.1:8080

class cherrypy._cpmodpy.ModPythonServer(loc='/', port=80, opts=None, apache_path='apache', handler='cherrypy._cpmodpy::handler')

Bases: object

start()
stop()
template = '\n# Apache2 server configuration file for running CherryPy with mod_python.\n\nDocumentRoot "/"\nListen %(port)s\nLoadModule python_module modules/mod_python.so\n\n<Location %(loc)s>\n SetHandler python-program\n PythonHandler %(handler)s\n PythonDebug On\n%(opts)s\n</Location>\n'
cherrypy._cpmodpy.handler(req)
cherrypy._cpmodpy.popen(fullcmd)
cherrypy._cpmodpy.read_process(cmd, args='')
cherrypy._cpmodpy.send_response(req, status, headers, body, stream=False)
cherrypy._cpmodpy.setup(req)

cherrypy._cpnative_server module

Native adapter for serving CherryPy via its builtin server.

class cherrypy._cpnative_server.CPHTTPServer(server_adapter=<cherrypy._cpserver.Server object at 0x7f3627f2a510>)

Bases: cherrypy.wsgiserver.wsgiserver2.HTTPServer

Wrapper for wsgiserver.HTTPServer.

wsgiserver has been designed to not reference CherryPy in any way, so that it can be used in other frameworks and applications. Therefore, we wrap it here, so we can apply some attributes from config -> cherrypy.server -> HTTPServer.

class cherrypy._cpnative_server.NativeGateway(req)

Bases: cherrypy.wsgiserver.wsgiserver2.Gateway

recursive = False
respond()
send_response(status, headers, body)

cherrypy._cpreqbody module

Request body processing for CherryPy.

New in version 3.2.

Application authors have complete control over the parsing of HTTP request entities. In short, cherrypy.request.body is now always set to an instance of RequestBody, and that class is a subclass of Entity.

When an HTTP request includes an entity body, it is often desirable to provide that information to applications in a form other than the raw bytes. Different content types demand different approaches. Examples:

  • For a GIF file, we want the raw bytes in a stream.
  • An HTML form is better parsed into its component fields, and each text field decoded from bytes to unicode.
  • A JSON body should be deserialized into a Python dict or list.

When the request contains a Content-Type header, the media type is used as a key to look up a value in the request.body.processors dict. If the full media type is not found, then the major type is tried; for example, if no processor is found for the ‘image/jpeg’ type, then we look for a processor for the ‘image’ types altogether. If neither the full type nor the major type has a matching processor, then a default processor is used (default_proc). For most types, this means no processing is done, and the body is left unread as a raw byte stream. Processors are configurable in an ‘on_start_resource’ hook.

Some processors, especially those for the ‘text’ types, attempt to decode bytes to unicode. If the Content-Type request header includes a ‘charset’ parameter, this is used to decode the entity. Otherwise, one or more default charsets may be attempted, although this decision is up to each processor. If a processor successfully decodes an Entity or Part, it should set the charset attribute on the Entity or Part to the name of the successful charset, so that applications can easily re-encode or transcode the value if they wish.

If the Content-Type of the request entity is of major type ‘multipart’, then the above parsing process, and possibly a decoding process, is performed for each part.

For both the full entity and multipart parts, a Content-Disposition header may be used to fill name and filename attributes on the request.body or the Part.

Custom Processors

You can add your own processors for any specific or major MIME type. Simply add it to the processors dict in a hook/tool that runs at on_start_resource or before_request_body. Here’s the built-in JSON tool for an example:

def json_in(force=True, debug=False):
    request = cherrypy.serving.request
    def json_processor(entity):
        """Read application/json data into request.json."""
        if not entity.headers.get("Content-Length", ""):
            raise cherrypy.HTTPError(411)

        body = entity.fp.read()
        try:
            request.json = json_decode(body)
        except ValueError:
            raise cherrypy.HTTPError(400, 'Invalid JSON document')
    if force:
        request.body.processors.clear()
        request.body.default_proc = cherrypy.HTTPError(
            415, 'Expected an application/json content type')
    request.body.processors['application/json'] = json_processor

We begin by defining a new json_processor function to stick in the processors dictionary. All processor functions take a single argument, the Entity instance they are to process. It will be called whenever a request is received (for those URI’s where the tool is turned on) which has a Content-Type of “application/json”.

First, it checks for a valid Content-Length (raising 411 if not valid), then reads the remaining bytes on the socket. The fp object knows its own length, so it won’t hang waiting for data that never arrives. It will return when all data has been read. Then, we decode those bytes using Python’s built-in json module, and stick the decoded result onto request.json . If it cannot be decoded, we raise 400.

If the “force” argument is True (the default), the Tool clears the processors dict so that request entities of other Content-Types aren’t parsed at all. Since there’s no entry for those invalid MIME types, the default_proc method of cherrypy.request.body is called. But this does nothing by default (usually to provide the page handler an opportunity to handle it.) But in our case, we want to raise 415, so we replace request.body.default_proc with the error (HTTPError instances, when called, raise themselves).

If we were defining a custom processor, we can do so without making a Tool. Just add the config entry:

request.body.processors = {'application/json': json_processor}

Note that you can only replace the processors dict wholesale this way, not update the existing one.

class cherrypy._cpreqbody.Entity(fp, headers, params=None, parts=None)

Bases: object

An HTTP request body, or MIME multipart body.

This class collects information about the HTTP request entity. When a given entity is of MIME type “multipart”, each part is parsed into its own Entity instance, and the set of parts stored in entity.parts.

Between the before_request_body and before_handler tools, CherryPy tries to process the request body (if any) by calling request.body.process. This uses the content_type of the Entity to look up a suitable processor in Entity.processors, a dict. If a matching processor cannot be found for the complete Content-Type, it tries again using the major type. For example, if a request with an entity of type “image/jpeg” arrives, but no processor can be found for that complete type, then one is sought for the major type “image”. If a processor is still not found, then the default_proc method of the Entity is called (which does nothing by default; you can override this too).

CherryPy includes processors for the “application/x-www-form-urlencoded” type, the “multipart/form-data” type, and the “multipart” major type. CherryPy 3.2 processes these types almost exactly as older versions. Parts are passed as arguments to the page handler using their Content-Disposition.name if given, otherwise in a generic “parts” argument. Each such part is either a string, or the Part itself if it’s a file. (In this case it will have file and filename attributes, or possibly a value attribute). Each Part is itself a subclass of Entity, and has its own process method and processors dict.

There is a separate processor for the “multipart” major type which is more flexible, and simply stores all multipart parts in request.body.parts. You can enable it with:

cherrypy.request.body.processors['multipart'] = _cpreqbody.process_multipart

in an on_start_resource tool.

attempt_charsets = ['utf-8']

A list of strings, each of which should be a known encoding.

When the Content-Type of the request body warrants it, each of the given encodings will be tried in order. The first one to successfully decode the entity without raising an error is stored as entity.charset. This defaults to ['utf-8'] (plus ‘ISO-8859-1’ for “text/*” types, as required by HTTP/1.1), but ['us-ascii', 'utf-8'] for multipart parts.

charset = None

The successful decoding; see “attempt_charsets” above.

content_type = None

The value of the Content-Type request header.

If the Entity is part of a multipart payload, this will be the Content-Type given in the MIME headers for this part.

default_content_type = 'application/x-www-form-urlencoded'

This defines a default Content-Type to use if no Content-Type header is given. The empty string is used for RequestBody, which results in the request body not being read or parsed at all. This is by design; a missing Content-Type header in the HTTP request entity is an error at best, and a security hole at worst. For multipart parts, however, the MIME spec declares that a part with no Content-Type defaults to “text/plain” (see Part).

default_proc()

Called if a more-specific processor is not found for the Content-Type.

filename = None

The Content-Disposition.filename header, if available.

fp = None

The readable socket file object.

fullvalue()

Return this entity as a string, whether stored in a file or not.

headers = None

A dict of request/multipart header names and values.

This is a copy of the request.headers for the request.body; for multipart parts, it is the set of headers for that part.

length = None

The value of the Content-Length header, if provided.

make_file()

Return a file-like object into which the request body will be read.

By default, this will return a TemporaryFile. Override as needed. See also cherrypy._cpreqbody.Part.maxrambytes.

name = None

The “name” parameter of the Content-Disposition header, if any.

next()
params = None

If the request Content-Type is ‘application/x-www-form-urlencoded’ or multipart, this will be a dict of the params pulled from the entity body; that is, it will be the portion of request.params that come from the message body (sometimes called “POST params”, although they can be sent with various HTTP method verbs). This value is set between the ‘before_request_body’ and ‘before_handler’ hooks (assuming that process_request_body is True).

part_class

The class used for multipart parts.

You can replace this with custom subclasses to alter the processing of multipart parts.

alias of Part

parts = None

A list of Part instances if Content-Type is of major type “multipart”.

process()

Execute the best-match processor for the given media type.

processors = {'multipart': <function process_multipart at 0x7f3627f50500>, 'multipart/form-data': <function process_multipart_form_data at 0x7f3627f50578>, 'application/x-www-form-urlencoded': <function process_urlencoded at 0x7f3627f878c0>}

A dict of Content-Type names to processor methods.

read(size=None, fp_out=None)
read_into_file(fp_out=None)

Read the request body into fp_out (or make_file() if None).

Return fp_out.

readline(size=None)
readlines(sizehint=None)
type

A deprecated alias for content_type.

class cherrypy._cpreqbody.Part(fp, headers, boundary)

Bases: cherrypy._cpreqbody.Entity

A MIME part entity, part of a multipart entity.

attempt_charsets = ['us-ascii', 'utf-8']

A list of strings, each of which should be a known encoding.

When the Content-Type of the request body warrants it, each of the given encodings will be tried in order. The first one to successfully decode the entity without raising an error is stored as entity.charset. This defaults to ['utf-8'] (plus ‘ISO-8859-1’ for “text/*” types, as required by HTTP/1.1), but ['us-ascii', 'utf-8'] for multipart parts.

boundary = None

The MIME multipart boundary.

default_content_type = 'text/plain'

This defines a default Content-Type to use if no Content-Type header is given. The empty string is used for RequestBody, which results in the request body not being read or parsed at all. This is by design; a missing Content-Type header in the HTTP request entity is an error at best, and a security hole at worst. For multipart parts, however (this class), the MIME spec declares that a part with no Content-Type defaults to “text/plain”.

default_proc()

Called if a more-specific processor is not found for the Content-Type.

classmethod from_fp(fp, boundary)
maxrambytes = 1000

The threshold of bytes after which point the Part will store its data in a file (generated by make_file) instead of a string. Defaults to 1000, just like the cgi module in Python’s standard library.

classmethod read_headers(fp)
read_into_file(fp_out=None)

Read the request body into fp_out (or make_file() if None).

Return fp_out.

read_lines_to_boundary(fp_out=None)

Read bytes from self.fp and return or write them to a file.

If the ‘fp_out’ argument is None (the default), all bytes read are returned in a single byte string.

If the ‘fp_out’ argument is not None, it must be a file-like object that supports the ‘write’ method; all bytes read will be written to the fp, and that fp is returned.

class cherrypy._cpreqbody.RequestBody(fp, headers, params=None, request_params=None)

Bases: cherrypy._cpreqbody.Entity

The entity of the HTTP request.

bufsize = 8192

The buffer size used when reading the socket.

default_content_type = ''

This defines a default Content-Type to use if no Content-Type header is given. The empty string is used for RequestBody, which results in the request body not being read or parsed at all. This is by design; a missing Content-Type header in the HTTP request entity is an error at best, and a security hole at worst. For multipart parts, however, the MIME spec declares that a part with no Content-Type defaults to “text/plain” (see Part).

maxbytes = None

Raise MaxSizeExceeded if more bytes than this are read from the socket.

process()

Process the request entity based on its Content-Type.

class cherrypy._cpreqbody.SizedReader(fp, length, maxbytes, bufsize=8192, has_trailers=False)
finish()
read(size=None, fp_out=None)

Read bytes from the request body and return or write them to a file.

A number of bytes less than or equal to the ‘size’ argument are read off the socket. The actual number of bytes read are tracked in self.bytes_read. The number may be smaller than ‘size’ when 1) the client sends fewer bytes, 2) the ‘Content-Length’ request header specifies fewer bytes than requested, or 3) the number of bytes read exceeds self.maxbytes (in which case, 413 is raised).

If the ‘fp_out’ argument is None (the default), all bytes read are returned in a single byte string.

If the ‘fp_out’ argument is not None, it must be a file-like object that supports the ‘write’ method; all bytes read will be written to the fp, and None is returned.

readline(size=None)

Read a line from the request body and return it.

readlines(sizehint=None)

Read lines from the request body and return them.

cherrypy._cpreqbody.process_multipart(entity)

Read all multipart parts into entity.parts.

cherrypy._cpreqbody.process_multipart_form_data(entity)

Read all multipart/form-data parts into entity.parts or entity.params.

cherrypy._cpreqbody.process_urlencoded(entity)

Read application/x-www-form-urlencoded data into entity.params.

cherrypy._cprequest module

class cherrypy._cprequest.Hook(callback, failsafe=None, priority=None, **kwargs)

Bases: object

A callback and its metadata: failsafe, priority, and kwargs.

callback = None

The bare callable that this Hook object is wrapping, which will be called when the Hook is called.

failsafe = False

If True, the callback is guaranteed to run even if other callbacks from the same call point raise exceptions.

kwargs = {}

A set of keyword arguments that will be passed to the callable on each call.

priority = 50

Defines the order of execution for a list of Hooks. Priority numbers should be limited to the closed interval [0, 100], but values outside this range are acceptable, as are fractional values.

class cherrypy._cprequest.HookMap(*a, **kw)

Bases: dict

A map of call points to lists of callbacks (Hook objects).

attach(point, callback, failsafe=None, priority=None, **kwargs)

Append a new Hook made from the supplied arguments.

copy()
run(point)

Execute all registered Hooks (callbacks) for the given point.

class cherrypy._cprequest.Request(local_host, remote_host, scheme='http', server_protocol='HTTP/1.1')

Bases: object

An HTTP request.

This object represents the metadata of an HTTP request message; that is, it contains attributes which describe the environment in which the request URL, headers, and body were sent (if you want tools to interpret the headers and body, those are elsewhere, mostly in Tools). This ‘metadata’ consists of socket data, transport characteristics, and the Request-Line. This object also contains data regarding the configuration in effect for the given URL, and the execution plan for generating a response.

app = None

The cherrypy.Application object which is handling this request.

base = ''

The (scheme://host) portion of the requested URL. In some cases (e.g. when proxying via mod_rewrite), this may contain path segments which cherrypy.url uses when constructing url’s, but which otherwise are ignored by CherryPy. Regardless, this value MUST NOT end in a slash.

body = None

If the request Content-Type is ‘application/x-www-form-urlencoded’ or multipart, this will be None. Otherwise, this will be an instance of RequestBody (which you can .read()); this value is set between the ‘before_request_body’ and ‘before_handler’ hooks (assuming that process_request_body is True).

body_params

If the request Content-Type is ‘application/x-www-form-urlencoded’ or multipart, this will be a dict of the params pulled from the entity body; that is, it will be the portion of request.params that come from the message body (sometimes called “POST params”, although they can be sent with various HTTP method verbs). This value is set between the ‘before_request_body’ and ‘before_handler’ hooks (assuming that process_request_body is True).

Deprecated in 3.2, will be removed for 3.3 in favor of request.body.params.

close()

Run cleanup code. (Core)

closed = False

True once the close method has been called, False otherwise.

config = None

A flat dict of all configuration entries which apply to the current request. These entries are collected from global config, application config (based on request.path_info), and from handler config (exactly how is governed by the request.dispatch object in effect for this request; by default, handler config can be attached anywhere in the tree between request.app.root and the final handler, and inherits downward).

cookie = <SimpleCookie: >

See help(Cookie).

dispatch = <cherrypy._cpdispatch.Dispatcher object at 0x7f3627f4ecd0>

The object which looks up the ‘page handler’ callable and collects config for the current request based on the path_info, other request attributes, and the application architecture. The core calls the dispatcher as early as possible, passing it a ‘path_info’ argument.

The default dispatcher discovers the page handler by matching path_info to a hierarchical arrangement of objects, starting at request.app.root. See help(cherrypy.dispatch) for more information.

error_page = {}

A dict of {error code: response filename or callable} pairs.

The error code must be an int representing a given HTTP error code, or the string ‘default’, which will be used if no matching entry is found for a given numeric code.

If a filename is provided, the file should contain a Python string- formatting template, and can expect by default to receive format values with the mapping keys %(status)s, %(message)s, %(traceback)s, and %(version)s. The set of format mappings can be extended by overriding HTTPError.set_response.

If a callable is provided, it will be called by default with keyword arguments ‘status’, ‘message’, ‘traceback’, and ‘version’, as for a string-formatting template. The callable must return a string or iterable of strings which will be set to response.body. It may also override headers or perform any other processing.

If no entry is given for an error code, and no ‘default’ entry exists, a default template will be used.

classmethod error_response()

The no-arg callable which will handle unexpected, untrapped errors during request processing. This is not used for expected exceptions (like NotFound, HTTPError, or HTTPRedirect) which are raised in response to expected conditions (those should be customized either via request.error_page or by overriding HTTPError.set_response). By default, error_response uses HTTPError(500) to return a generic error response to the user-agent.

get_resource(path)

Call a dispatcher (which sets self.handler and .config). (Core)

handle_error()

Handle the last unanticipated exception. (Core)

handler = None

The function, method, or other callable which CherryPy will call to produce the response. The discovery of the handler and the arguments it will receive are determined by the request.dispatch object. By default, the handler is discovered by walking a tree of objects starting at request.app.root, and is then passed all HTTP params (from the query string and POST body) as keyword arguments.

header_list = []

A list of the HTTP request headers as (name, value) tuples. In general, you should use request.headers (a dict) instead.

headers = {}

A dict-like object containing the request headers. Keys are header names (in Title-Case format); however, you may get and set them in a case-insensitive manner. That is, headers[‘Content-Type’] and headers[‘content-type’] refer to the same value. Values are header values (decoded according to RFC 2047 if necessary). See also: httputil.HeaderMap, httputil.HeaderElement.

hooks = cherrypy._cprequest.HookMap(points=['before_error_response', 'on_end_resource', 'on_end_request', 'before_finalize', 'before_handler', 'after_error_response', 'on_start_resource', 'before_request_body'])

A HookMap (dict-like object) of the form: {hookpoint: [hook, ...]}. Each key is a str naming the hook point, and each value is a list of hooks which will be called at that hook point during this request. The list of hooks is generally populated as early as possible (mostly from Tools specified in config), but may be extended at any time. See also: _cprequest.Hook, _cprequest.HookMap, and cherrypy.tools.

is_index = None

This will be True if the current request is mapped to an ‘index’ resource handler (also, a ‘default’ handler if path_info ends with a slash). The value may be used to automatically redirect the user-agent to a ‘more canonical’ URL which either adds or removes the trailing slash. See cherrypy.tools.trailing_slash.

local = httputil.Host('127.0.0.1', 80, '127.0.0.1')

An httputil.Host(ip, port, hostname) object for the server socket.

login = None

When authentication is used during the request processing this is set to ‘False’ if it failed and to the ‘username’ value if it succeeded. The default ‘None’ implies that no authentication happened.

method = 'GET'

Indicates the HTTP method to be performed on the resource identified by the Request-URI. Common methods include GET, HEAD, POST, PUT, and DELETE. CherryPy allows any extension method; however, various HTTP servers and gateways may restrict the set of allowable methods. CherryPy applications SHOULD restrict the set (on a per-URI basis).

methods_with_bodies = ('POST', 'PUT')

A sequence of HTTP methods for which CherryPy will automatically attempt to read a body from the rfile. If you are going to change this property, modify it on the configuration (recommended) or on the “hook point” on_start_resource.

namespaces = cherrypy.lib.reprconf.NamespaceSet({'hooks': <function hooks_namespace at 0x7f3627eec6e0>, 'error_page': <function error_page_namespace at 0x7f3627eecd70>, 'request': <function request_namespace at 0x7f3627eecc80>, 'response': <function response_namespace at 0x7f3627eeccf8>, 'tools': <cherrypy._cptools.Toolbox object at 0x7f3627fa65d0>})
params = {}

A dict which combines query string (GET) and request entity (POST) variables. This is populated in two stages: GET params are added before the ‘on_start_resource’ hook, and POST params are added between the ‘before_request_body’ and ‘before_handler’ hooks.

path_info = '/'

The ‘relative path’ portion of the Request-URI. This is relative to the script_name (‘mount point’) of the application which is handling this request.

prev = None

The previous Request object (if any). This should be None unless we are processing an InternalRedirect.

process_headers()

Parse HTTP header data into Python structures. (Core)

process_query_string()

Parse the query string into Python structures. (Core)

process_request_body = True

If True, the rfile (if any) is automatically read and parsed, and the result placed into request.params or request.body.

protocol = (1, 1)

The HTTP protocol version corresponding to the set of features which should be allowed in the response. If BOTH the client’s request message AND the server’s level of HTTP compliance is HTTP/1.1, this attribute will be the tuple (1, 1). If either is 1.0, this attribute will be the tuple (1, 0). Lower HTTP protocol versions are not explicitly supported.

query_string = ''

The query component of the Request-URI, a string of information to be interpreted by the resource. The query portion of a URI follows the path component, and is separated by a ‘?’. For example, the URI ‘http://www.cherrypy.org/wiki?a=3&b=4‘ has the query component, ‘a=3&b=4’.

query_string_encoding = 'utf8'

The encoding expected for query string arguments after % HEX HEX decoding). If a query string is provided that cannot be decoded with this encoding, 404 is raised (since technically it’s a different URI). If you want arbitrary encodings to not error, set this to ‘Latin-1’; you can then encode back to bytes and re-decode to whatever encoding you like later.

remote = httputil.Host('127.0.0.1', 1111, '127.0.0.1')

An httputil.Host(ip, port, hostname) object for the client socket.

request_line = ''

The complete Request-Line received from the client. This is a single string consisting of the request method, URI, and protocol version (joined by spaces). Any final CRLF is removed.

respond(path_info)

Generate a response for the resource at self.path_info. (Core)

rfile = None

If the request included an entity (body), it will be available as a stream in this attribute. However, the rfile will normally be read for you between the ‘before_request_body’ hook and the ‘before_handler’ hook, and the resulting string is placed into either request.params or the request.body attribute.

You may disable the automatic consumption of the rfile by setting request.process_request_body to False, either in config for the desired path, or in an ‘on_start_resource’ or ‘before_request_body’ hook.

WARNING: In almost every case, you should not attempt to read from the rfile stream after CherryPy’s automatic mechanism has read it. If you turn off the automatic parsing of rfile, you should read exactly the number of bytes specified in request.headers[‘Content-Length’]. Ignoring either of these warnings may result in a hung request thread or in corruption of the next (pipelined) request.

run(method, path, query_string, req_protocol, headers, rfile)

Process the Request. (Core)

method, path, query_string, and req_protocol should be pulled directly from the Request-Line (e.g. “GET /path?key=val HTTP/1.0”).

path

This should be %XX-unquoted, but query_string should not be.

When using Python 2, they both MUST be byte strings, not unicode strings.

When using Python 3, they both MUST be unicode strings, not byte strings, and preferably not bytes x00-xFF disguised as unicode.

headers
A list of (name, value) tuples.
rfile
A file-like object containing the HTTP request entity.

When run() is done, the returned object should have 3 attributes:

  • status, e.g. “200 OK”
  • header_list, a list of (name, value) tuples
  • body, an iterable yielding strings

Consumer code (HTTP servers) should then access these response attributes to build the outbound stream.

scheme = 'http'

The protocol used between client and server. In most cases, this will be either ‘http’ or ‘https’.

script_name = ''

The ‘mount point’ of the application which is handling this request.

This attribute MUST NOT end in a slash. If the script_name refers to the root of the URI, it MUST be an empty string (not “/”).

server_protocol = 'HTTP/1.1'

The HTTP version for which the HTTP server is at least conditionally compliant.

show_mismatched_params = True

If True, mismatched parameters encountered during PageHandler invocation processing will be included in the response body.

show_tracebacks = True

If True, unexpected errors encountered during request processing will include a traceback in the response body.

stage = None

A string containing the stage reached in the request-handling process. This is useful when debugging a live server with hung requests.

throw_errors = False

If True, Request.run will not trap any errors (except HTTPRedirect and HTTPError, which are more properly called ‘exceptions’, not errors).

throws = (<type 'exceptions.KeyboardInterrupt'>, <type 'exceptions.SystemExit'>, <class 'cherrypy._cperror.InternalRedirect'>)

The sequence of exceptions which Request.run does not trap.

toolmaps = {}

A nested dict of all Toolboxes and Tools in effect for this request, of the form: {Toolbox.namespace: {Tool.name: config dict}}.

class cherrypy._cprequest.Response

Bases: object

An HTTP Response, including status, headers, and body.

body

The body (entity) of the HTTP response.

check_timeout()

If now > self.time + self.timeout, set self.timed_out.

This purposefully sets a flag, rather than raising an error, so that a monitor thread can interrupt the Response thread.

collapse_body()

Collapse self.body to a single string; replace it and return it.

cookie = <SimpleCookie: >

See help(Cookie).

finalize()

Transform headers (and cookies) into self.header_list. (Core)

header_list = []

A list of the HTTP response headers as (name, value) tuples. In general, you should use response.headers (a dict) instead. This attribute is generated from response.headers and is not valid until after the finalize phase.

headers = {}

A dict-like object containing the response headers. Keys are header names (in Title-Case format); however, you may get and set them in a case-insensitive manner. That is, headers[‘Content-Type’] and headers[‘content-type’] refer to the same value. Values are header values (decoded according to RFC 2047 if necessary).

See also

classes HeaderMap, HeaderElement

status = ''

The HTTP Status-Code and Reason-Phrase.

stream = False

If False, buffer the response body.

time = None

The value of time.time() when created. Use in HTTP dates.

timed_out = False

Flag to indicate the response should be aborted, because it has exceeded its timeout.

timeout = 300

Seconds after which the response will be aborted.

class cherrypy._cprequest.ResponseBody

Bases: object

The body of the HTTP response (the response entity).

cherrypy._cprequest.error_page_namespace(k, v)

Attach error pages declared in config.

cherrypy._cprequest.hooks_namespace(k, v)

Attach bare hooks declared in config.

cherrypy._cprequest.request_namespace(k, v)

Attach request attributes declared in config.

cherrypy._cprequest.response_namespace(k, v)

Attach response attributes declared in config.

cherrypy._cpserver module

Manage HTTP servers with CherryPy.

class cherrypy._cpserver.Server

Bases: cherrypy.process.servers.ServerAdapter

An adapter for an HTTP server.

You can set attributes (like socket_host and socket_port) on this object (which is probably cherrypy.server), and call quickstart. For example:

cherrypy.server.socket_port = 80
cherrypy.quickstart()
base()

Return the base (scheme://host[:port] or sock file) for this server.

bind_addr

A (host, port) tuple for TCP sockets or a str for Unix domain sockets.

httpserver_from_self(httpserver=None)

Return a (httpserver, bind_addr) pair based on self attributes.

instance = None

If not None, this should be an HTTP server instance (such as CPWSGIServer) which cherrypy.server will control. Use this when you need more control over object instantiation than is available in the various configuration options.

max_request_body_size = 104857600

The maximum number of bytes allowable in the request body. If exceeded, the HTTP server should return “413 Request Entity Too Large”.

max_request_header_size = 512000

The maximum number of bytes allowable in the request headers. If exceeded, the HTTP server should return “413 Request Entity Too Large”.

nodelay = True

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

protocol_version = 'HTTP/1.1'

The version string to write in the Status-Line of all HTTP responses, for example, “HTTP/1.1” (the default). Depending on the HTTP server used, this should also limit the supported features used in the response.

shutdown_timeout = 5

The time to wait for HTTP worker threads to clean up.

socket_file = None

If given, the name of the UNIX socket to use instead of TCP/IP.

When this option is not None, the socket_host and socket_port options are ignored.

socket_host

The hostname or IP address on which to listen for connections.

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.

socket_port = 8080

The TCP port on which to listen for connections.

socket_queue_size = 5

The ‘backlog’ argument to socket.listen(); specifies the maximum number of queued connections (default 5).

socket_timeout = 10

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

ssl_certificate = None

The filename of the SSL certificate to use.

ssl_certificate_chain = None

When using PyOpenSSL, the certificate chain to pass to Context.load_verify_locations.

ssl_context = None

When using PyOpenSSL, an instance of SSL.Context.

ssl_module = 'pyopenssl'

The name of a registered SSL adaptation module to use with the builtin WSGI server. Builtin options are ‘builtin’ (to use the SSL library built into recent versions of Python) and ‘pyopenssl’ (to use the PyOpenSSL project, which you must install separately). You may also register your own classes in the wsgiserver.ssl_adapters dict.

ssl_private_key = None

The filename of the private key to use with SSL.

start()

Start the HTTP server.

statistics = False

Turns statistics-gathering on or off for aware HTTP servers.

thread_pool = 10

The number of worker threads to start up in the pool.

thread_pool_max = -1

The maximum size of the worker-thread pool. Use -1 to indicate no limit.

wsgi_version = (1, 0)

The WSGI version tuple to use with the builtin WSGI server. The provided options are (1, 0) [which includes support for PEP 3333, which declares it covers WSGI version 1.0.1 but still mandates the wsgi.version (1, 0)] and (‘u’, 0), an experimental unicode version. You may create and register your own experimental versions of the WSGI protocol by adding custom classes to the wsgiserver.wsgi_gateways dict.

cherrypy._cpthreadinglocal module

Thread-local objects

(Note that this module provides a Python version of thread
threading.local class. Depending on the version of Python you’re using, there may be a faster one available. You should always import the local class from threading.)

Thread-local objects support the management of thread-local data. If you have data that you want to be local to a thread, simply create a thread-local object and use its attributes:

>>> mydata = local()
>>> mydata.number = 42
>>> mydata.number
42

You can also access the local-object’s dictionary:

>>> mydata.__dict__
{'number': 42}
>>> mydata.__dict__.setdefault('widgets', [])
[]
>>> mydata.widgets
[]

What’s important about thread-local objects is that their data are local to a thread. If we access the data in a different thread:

>>> log = []
>>> def f():
...     items = mydata.__dict__.items()
...     items.sort()
...     log.append(items)
...     mydata.number = 11
...     log.append(mydata.number)
>>> import threading
>>> thread = threading.Thread(target=f)
>>> thread.start()
>>> thread.join()
>>> log
[[], 11]

we get different data. Furthermore, changes made in the other thread don’t affect data seen in this thread:

>>> mydata.number
42

Of course, values you get from a local object, including a __dict__ attribute, are for whatever thread was current at the time the attribute was read. For that reason, you generally don’t want to save these values across threads, as they apply only to the thread they came from.

You can create custom local objects by subclassing the local class:

>>> class MyLocal(local):
...     number = 2
...     initialized = False
...     def __init__(self, **kw):
...         if self.initialized:
...             raise SystemError('__init__ called too many times')
...         self.initialized = True
...         self.__dict__.update(kw)
...     def squared(self):
...         return self.number ** 2

This can be useful to support default values, methods and initialization. Note that if you define an __init__ method, it will be called each time the local object is used in a separate thread. This is necessary to initialize each thread’s dictionary.

Now if we create a local object:

>>> mydata = MyLocal(color='red')

Now we have a default number:

>>> mydata.number
2

an initial color:

>>> mydata.color
'red'
>>> del mydata.color

And a method that operates on the data:

>>> mydata.squared()
4

As before, we can access the data in a separate thread:

>>> log = []
>>> thread = threading.Thread(target=f)
>>> thread.start()
>>> thread.join()
>>> log
[[('color', 'red'), ('initialized', True)], 11]

without affecting this thread’s data:

>>> mydata.number
2
>>> mydata.color
Traceback (most recent call last):
...
AttributeError: 'MyLocal' object has no attribute 'color'

Note that subclasses can define slots, but they are not thread local. They are shared across threads:

>>> class MyLocal(local):
...     __slots__ = 'number'
>>> mydata = MyLocal()
>>> mydata.number = 42
>>> mydata.color = 'red'

So, the separate thread:

>>> thread = threading.Thread(target=f)
>>> thread.start()
>>> thread.join()

affects what we see:

>>> mydata.number
11
>>> del mydata
class cherrypy._cpthreadinglocal.local

Bases: cherrypy._cpthreadinglocal._localbase

cherrypy._cptools module

CherryPy tools. A “tool” is any helper, adapted to CP.

Tools are usually designed to be used in a variety of ways (although some may only offer one if they choose):

Library calls
All tools are callables that can be used wherever needed. The arguments are straightforward and should be detailed within the docstring.
Function decorators
All tools, when called, may be used as decorators which configure individual CherryPy page handlers (methods on the CherryPy tree). That is, “@tools.anytool()” should “turn on” the tool via the decorated function’s _cp_config attribute.
CherryPy config
If a tool exposes a “_setup” callable, it will be called once per Request (if the feature is “turned on” via config).

Tools may be implemented as any object with a namespace. The builtins are generally either modules or instances of the tools.Tool class.

class cherrypy._cptools.CachingTool(point, callable, name=None, priority=50)

Bases: cherrypy._cptools.Tool

Caching Tool for CherryPy.

class cherrypy._cptools.DeprecatedTool(point, warnmsg=None)

Bases: cherrypy._cptools.Tool

warnmsg = 'This Tool is deprecated.'
class cherrypy._cptools.ErrorTool(callable, name=None)

Bases: cherrypy._cptools.Tool

Tool which is used to replace the default request.error_response.

class cherrypy._cptools.HandlerTool(callable, name=None)

Bases: cherrypy._cptools.Tool

Tool which is called ‘before main’, that may skip normal handlers.

If the tool successfully handles the request (by setting response.body), if should return True. This will cause CherryPy to skip any ‘normal’ page handler. If the tool did not handle the request, it should return False to tell CherryPy to continue on and call the normal page handler. If the tool is declared AS a page handler (see the ‘handler’ method), returning False will raise NotFound.

handler(*args, **kwargs)

Use this tool as a CherryPy page handler.

For example:

class Root:
    nav = tools.staticdir.handler(section="/nav", dir="nav",
                                  root=absDir)
class cherrypy._cptools.HandlerWrapperTool(newhandler, point='before_handler', name=None, priority=50)

Bases: cherrypy._cptools.Tool

Tool which wraps request.handler in a provided wrapper function.

The ‘newhandler’ arg must be a handler wrapper function that takes a ‘next_handler’ argument, plus *args and **kwargs. Like all page handler functions, it must return an iterable for use as cherrypy.response.body.

For example, to allow your ‘inner’ page handlers to return dicts which then get interpolated into a template:

def interpolator(next_handler, *args, **kwargs):
    filename = cherrypy.request.config.get('template')
    cherrypy.response.template = env.get_template(filename)
    response_dict = next_handler(*args, **kwargs)
    return cherrypy.response.template.render(**response_dict)
cherrypy.tools.jinja = HandlerWrapperTool(interpolator)
callable(debug=False)
class cherrypy._cptools.SessionAuthTool(callable, name=None)

Bases: cherrypy._cptools.HandlerTool

class cherrypy._cptools.SessionTool

Bases: cherrypy._cptools.Tool

Session Tool for CherryPy.

sessions.locking

When ‘implicit’ (the default), the session will be locked for you, just before running the page handler.

When ‘early’, the session will be locked before reading the request body. This is off by default for safety reasons; for example, a large upload would block the session, denying an AJAX progress meter (issue).

When ‘explicit’ (or any other value), you need to call cherrypy.session.acquire_lock() yourself before using session data.

regenerate()

Drop the current session and make a new one (with a new id).

class cherrypy._cptools.Tool(point, callable, name=None, priority=50)

Bases: object

A registered function for use with CherryPy request-processing hooks.

help(tool.callable) should give you more information about this Tool.

namespace = 'tools'
on
class cherrypy._cptools.Toolbox(namespace)

Bases: object

A collection of Tools.

This object also functions as a config namespace handler for itself. Custom toolboxes should be added to each Application’s toolboxes dict.

class cherrypy._cptools.XMLRPCController

Bases: object

A Controller (page handler collection) for XML-RPC.

To use it, have your controllers subclass this base class (it will turn on the tool for you).

You can also supply the following optional config entries:

tools.xmlrpc.encoding: 'utf-8'
tools.xmlrpc.allow_none: 0

XML-RPC is a rather discontinuous layer over HTTP; dispatching to the appropriate handler must first be performed according to the URL, and then a second dispatch step must take place according to the RPC method specified in the request body. It also allows a superfluous “/RPC2” prefix in the URL, supplies its own handler args in the body, and requires a 200 OK “Fault” response instead of 404 when the desired method is not found.

Therefore, XML-RPC cannot be implemented for CherryPy via a Tool alone. This Controller acts as the dispatch target for the first half (based on the URL); it then reads the RPC method from the request body and does its own second dispatch step based on that method. It also reads body params, and returns a Fault on error.

The XMLRPCDispatcher strips any /RPC2 prefix; if you aren’t using /RPC2 in your URL’s, you can safely skip turning on the XMLRPCDispatcher. Otherwise, you need to use declare it in config:

request.dispatch: cherrypy.dispatch.XMLRPCDispatcher()
default(*vpath, **params)

cherrypy._cptree module

CherryPy Application and Tree objects.

class cherrypy._cptree.Application(root, script_name='', config=None)

Bases: object

A CherryPy Application.

Servers and gateways should not instantiate Request objects directly. Instead, they should ask an Application object for a request object.

An instance of this class may also be used as a WSGI callable (WSGI application object) for itself.

config = {}

A dict of {path: pathconf} pairs, where ‘pathconf’ is itself a dict of {key: value} pairs.

find_config(path, key, default=None)

Return the most-specific value for key along path, or default.

get_serving(local, remote, scheme, sproto)

Create and return a Request and Response object.

log = None

A LogManager instance. See _cplogging.

merge(config)

Merge the given config into self.config.

namespaces = cherrypy.lib.reprconf.NamespaceSet({})
relative_urls = False
release_serving()

Release the current serving (request and response).

request_class

alias of Request

response_class

alias of Response

root = None

The top-most container of page handlers for this app. Handlers should be arranged in a hierarchy of attributes, matching the expected URI hierarchy; the default dispatcher then searches this hierarchy for a matching handler. When using a dispatcher other than the default, this value may be None.

script_name

The URI “mount point” for this app. A mount point is that portion of the URI which is constant for all URIs that are serviced by this application; it does not include scheme, host, or proxy (“virtual host”) portions of the URI.

For example, if script_name is “/my/cool/app”, then the URL “http://www.example.com/my/cool/app/page1” might be handled by a “page1” method on the root object.

The value of script_name MUST NOT end in a slash. If the script_name refers to the root of the URI, it MUST be an empty string (not “/”).

If script_name is explicitly set to None, then the script_name will be provided for each call from request.wsgi_environ[‘SCRIPT_NAME’].

script_name_doc = 'The URI "mount point" for this app. A mount point\n is that portion of the URI which is constant for all URIs that are\n serviced by this application; it does not include scheme, host, or proxy\n ("virtual host") portions of the URI.\n\n For example, if script_name is "/my/cool/app", then the URL\n "http://www.example.com/my/cool/app/page1" might be handled by a\n "page1" method on the root object.\n\n The value of script_name MUST NOT end in a slash. If the script_name\n refers to the root of the URI, it MUST be an empty string (not "/").\n\n If script_name is explicitly set to None, then the script_name will be\n provided for each call from request.wsgi_environ[\'SCRIPT_NAME\'].\n '
toolboxes = {'tools': <cherrypy._cptools.Toolbox object at 0x7f3627fa65d0>}
wsgiapp = None

A CPWSGIApp instance. See _cpwsgi.

class cherrypy._cptree.Tree

Bases: object

A registry of CherryPy applications, mounted at diverse points.

An instance of this class may also be used as a WSGI callable (WSGI application object), in which case it dispatches to all mounted apps.

apps = {}

A dict of the form {script name: application}, where “script name” is a string declaring the URI mount point (no trailing slash), and “application” is an instance of cherrypy.Application (or an arbitrary WSGI callable if you happen to be using a WSGI server).

graft(wsgi_callable, script_name='')

Mount a wsgi callable at the given script_name.

mount(root, script_name='', config=None)

Mount a new app from a root object, script_name, and config.

root
An instance of a “controller class” (a collection of page handler methods) which represents the root of the application. This may also be an Application instance, or None if using a dispatcher other than the default.
script_name

A string containing the “mount point” of the application. This should start with a slash, and be the path portion of the URL at which to mount the given root. For example, if root.index() will handle requests to “http://www.example.com:8080/dept/app1/”, then the script_name argument would be “/dept/app1”.

It MUST NOT end in a slash. If the script_name refers to the root of the URI, it MUST be an empty string (not “/”).

config
A file or dict containing application config.
script_name(path=None)

The script_name of the app at the given path, or None.

If path is None, cherrypy.request is used.

cherrypy._cpwsgi module

WSGI interface (see PEP 333 and 3333).

Note that WSGI environ keys and values are ‘native strings’; that is, whatever the type of “” is. For Python 2, that’s a byte string; for Python 3, it’s a unicode string. But PEP 3333 says: “even if Python’s str type is actually Unicode “under the hood”, the content of native strings must still be translatable to bytes via the Latin-1 encoding!”

class cherrypy._cpwsgi.AppResponse(environ, start_response, cpapp)

Bases: object

WSGI response iterable for CherryPy applications.

close()

Close and de-reference the current request and response. (Core)

headerNames = {'CONTENT_LENGTH': 'Content-Length', 'REMOTE_HOST': 'Remote-Host', 'CONTENT_TYPE': 'Content-Type', 'HTTP_CGI_AUTHORIZATION': 'Authorization', 'REMOTE_ADDR': 'Remote-Addr'}
next()
run()

Create a Request object using environ.

translate_headers(environ)

Translate CGI-environ header names to HTTP header names.

class cherrypy._cpwsgi.CPWSGIApp(cpapp, pipeline=None)

Bases: object

A WSGI application object for a CherryPy Application.

config = {}

A dict whose keys match names listed in the pipeline. Each value is a further dict which will be passed to the corresponding named WSGI callable (from the pipeline) as keyword arguments.

head = None

Rather than nest all apps in the pipeline on each call, it’s only done the first time, and the result is memoized into self.head. Set this to None again if you change self.pipeline after calling self.

namespace_handler(k, v)

Config handler for the ‘wsgi’ namespace.

pipeline = [('ExceptionTrapper', <class 'cherrypy._cpwsgi.ExceptionTrapper'>), ('InternalRedirector', <class 'cherrypy._cpwsgi.InternalRedirector'>)]

A list of (name, wsgiapp) pairs. Each ‘wsgiapp’ MUST be a constructor that takes an initial, positional ‘nextapp’ argument, plus optional keyword arguments, and returns a WSGI application (that takes environ and start_response arguments). The ‘name’ can be any you choose, and will correspond to keys in self.config.

response_class

The class to instantiate and return as the next app in the WSGI chain.

alias of AppResponse

tail(environ, start_response)

WSGI application callable for the actual CherryPy application.

You probably shouldn’t call this; call self.__call__ instead, so that any WSGI middleware in self.pipeline can run first.

class cherrypy._cpwsgi.ExceptionTrapper(nextapp, throws=(<type 'exceptions.KeyboardInterrupt'>, <type 'exceptions.SystemExit'>))

Bases: object

WSGI middleware that traps exceptions.

class cherrypy._cpwsgi.InternalRedirector(nextapp, recursive=False)

Bases: object

WSGI middleware that handles raised cherrypy.InternalRedirect.

class cherrypy._cpwsgi.VirtualHost(default, domains=None, use_x_forwarded_host=True)

Bases: object

Select a different WSGI application based on the Host header.

This can be useful when running multiple sites within one CP server. It allows several domains to point to different applications. For example:

root = Root()
RootApp = cherrypy.Application(root)
Domain2App = cherrypy.Application(root)
SecureApp = cherrypy.Application(Secure())

vhost = cherrypy._cpwsgi.VirtualHost(RootApp,
    domains={'www.domain2.example': Domain2App,
             'www.domain2.example:443': SecureApp,
             })

cherrypy.tree.graft(vhost)
default = None

Required. The default WSGI application.

domains = {}

A dict of {host header value: application} pairs. The incoming “Host” request header is looked up in this dict, and, if a match is found, the corresponding WSGI application will be called instead of the default. Note that you often need separate entries for “example.com” and “www.example.com”. In addition, “Host” headers may contain the port number.

use_x_forwarded_host = True

If True (the default), any “X-Forwarded-Host” request header will be used instead of the “Host” header. This is commonly added by HTTP servers (such as Apache) when proxying.

cherrypy._cpwsgi.downgrade_wsgi_ux_to_1x(environ)

Return a new environ dict for WSGI 1.x from the given WSGI u.x environ.

cherrypy._cpwsgi_server module

WSGI server interface (see PEP 333). This adds some CP-specific bits to the framework-agnostic wsgiserver package.

class cherrypy._cpwsgi_server.CPWSGIServer(server_adapter=<cherrypy._cpserver.Server object at 0x7f3627f2a510>)

Bases: cherrypy.wsgiserver.wsgiserver2.CherryPyWSGIServer

Wrapper for wsgiserver.CherryPyWSGIServer.

wsgiserver has been designed to not reference CherryPy in any way, so that it can be used in other frameworks and applications. Therefore, we wrap it here, so we can set our own mount points from cherrypy.tree and apply some attributes from config -> cherrypy.server -> wsgiserver.

error_log(msg='', level=20, traceback=False)

Module contents

CherryPy is a pythonic, object-oriented HTTP framework.

CherryPy consists of not one, but four separate API layers.

The APPLICATION LAYER is the simplest. CherryPy applications are written as a tree of classes and methods, where each branch in the tree corresponds to a branch in the URL path. Each method is a ‘page handler’, which receives GET and POST params as keyword arguments, and returns or yields the (HTML) body of the response. The special method name ‘index’ is used for paths that end in a slash, and the special method name ‘default’ is used to handle multiple paths via a single handler. This layer also includes:

  • the ‘exposed’ attribute (and cherrypy.expose)
  • cherrypy.quickstart()
  • _cp_config attributes
  • cherrypy.tools (including cherrypy.session)
  • cherrypy.url()

The ENVIRONMENT LAYER is used by developers at all levels. It provides information about the current request and response, plus the application and server environment, via a (default) set of top-level objects:

  • cherrypy.request
  • cherrypy.response
  • cherrypy.engine
  • cherrypy.server
  • cherrypy.tree
  • cherrypy.config
  • cherrypy.thread_data
  • cherrypy.log
  • cherrypy.HTTPError, NotFound, and HTTPRedirect
  • cherrypy.lib

The EXTENSION LAYER allows advanced users to construct and share their own plugins. It consists of:

  • Hook API
  • Tool API
  • Toolbox API
  • Dispatch API
  • Config Namespace API

Finally, there is the CORE LAYER, which uses the core API’s to construct the default components which are available at higher layers. You can think of the default components as the ‘reference implementation’ for CherryPy. Megaframeworks (and advanced users) may replace the default components with customized or extended components. The core API’s are:

  • Application API
  • Engine API
  • Request API
  • Server API
  • WSGI API

These API’s are described in the CherryPy specification.

cherrypy.expose(func=None, alias=None)

Expose the function, optionally providing an alias or set of aliases.

cherrypy.popargs(*args, **kwargs)

A decorator for _cp_dispatch (cherrypy.dispatch.Dispatcher.dispatch_method_name).

Optional keyword argument: handler=(Object or Function)

Provides a _cp_dispatch function that pops off path segments into cherrypy.request.params under the names specified. The dispatch is then forwarded on to the next vpath element.

Note that any existing (and exposed) member function of the class that popargs is applied to will override that value of the argument. For instance, if you have a method named “list” on the class decorated with popargs, then accessing “/list” will call that function instead of popping it off as the requested parameter. This restriction applies to all _cp_dispatch functions. The only way around this restriction is to create a “blank class” whose only function is to provide _cp_dispatch.

If there are path elements after the arguments, or more arguments are requested than are available in the vpath, then the ‘handler’ keyword argument specifies the next object to handle the parameterized request. If handler is not specified or is None, then self is used. If handler is a function rather than an instance, then that function will be called with the args specified and the return value from that function used as the next object INSTEAD of adding the parameters to cherrypy.request.args.

This decorator may be used in one of two ways:

As a class decorator: @cherrypy.popargs(‘year’, ‘month’, ‘day’) class Blog:

def index(self, year=None, month=None, day=None):
#Process the parameters here; any url like #/, /2009, /2009/12, or /2009/12/31 #will fill in the appropriate parameters.
def create(self):
#This link will still be available at /create. Defined functions #take precedence over arguments.

Or as a member of a class: class Blog:

_cp_dispatch = cherrypy.popargs(‘year’, ‘month’, ‘day’) #...

The handler argument may be used to mix arguments with built in functions. For instance, the following setup allows different activities at the day, month, and year level:

class DayHandler:
def index(self, year, month, day):
#Do something with this day; probably list entries
def delete(self, year, month, day):
#Delete all entries for this day

@cherrypy.popargs(‘day’, handler=DayHandler()) class MonthHandler:

def index(self, year, month):
#Do something with this month; probably list entries
def delete(self, year, month):
#Delete all entries for this month

@cherrypy.popargs(‘month’, handler=MonthHandler()) class YearHandler:

def index(self, year):
#Do something with this year

#...

@cherrypy.popargs(‘year’, handler=YearHandler()) class Root:

def index(self):
#...
cherrypy.quickstart(root=None, script_name='', config=None)

Mount the given root, start the builtin server (and engine), then block.

root: an instance of a “controller class” (a collection of page handler
methods) which represents the root of the application.
script_name: a string containing the “mount point” of the application.

This should start with a slash, and be the path portion of the URL at which to mount the given root. For example, if root.index() will handle requests to “http://www.example.com:8080/dept/app1/”, then the script_name argument would be “/dept/app1”.

It MUST NOT end in a slash. If the script_name refers to the root of the URI, it MUST be an empty string (not “/”).

config: a file or dict containing application config. If this contains
a [global] section, those entries will be used in the global (site-wide) config.
cherrypy.url(path='', qs='', script_name=None, base=None, relative=None)

Create an absolute URL for the given path.

If ‘path’ starts with a slash (‘/’), this will return
(base + script_name + path + qs).
If it does not start with a slash, this returns
(base + script_name [+ request.path_info] + path + qs).

If script_name is None, cherrypy.request will be used to find a script_name, if available.

If base is None, cherrypy.request.base will be used (if available). Note that you can use cherrypy.tools.proxy to change this.

Finally, note that this function can be used to obtain an absolute URL for the current request path (minus the querystring) by passing no args. If you call url(qs=cherrypy.request.query_string), you should get the original browser URL (assuming no internal redirections).

If relative is None or not provided, request.app.relative_urls will be used (if available, else False). If False, the output will be an absolute URL (including the scheme, host, vhost, and script_name). If True, the output will instead be a URL that is relative to the current request path, perhaps including ‘..’ atoms. If relative is the string ‘server’, the output will instead be a URL that is relative to the server root; i.e., it will start with a slash.