cherrypy package

Subpackages

Submodules

cherrypy.daemon module

The CherryPy daemon.

cherrypy.daemon.run()[source]

Run cherryd CLI.

cherrypy.daemon.start(configfiles=None, daemonize=False, environment=None, fastcgi=False, scgi=False, pidfile=None, imports=None, cgi=False)[source]

Subscribe all engine plugins and start the engine.

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.

exception cherrypy.HTTPError(status=500, message=None)[source]

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
get_error_page(*args, **kwargs)[source]
classmethod handle(exception, status=500, message='')[source]

Translate exception into an HTTPError.

reason = None
set_response()[source]

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
exception cherrypy.HTTPRedirect(urls, status=None, encoding=None)[source]

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 redirectingpost for additional caveats.

encoding = 'utf-8'
set_response()[source]

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
urls = None
exception cherrypy.InternalRedirect(path, query_string='')[source]

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.NotFound(path=None)[source]

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.CherryPyException[source]

Bases: Exception

A base class for CherryPy exceptions.

exception cherrypy.TimeoutError[source]

Bases: cherrypy._cperror.CherryPyException

Exception raised when Response.timed_out is detected.

class cherrypy.Tool(point, callable, name=None, priority=50)[source]

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.Application(root, script_name='', config=None)[source]

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 = {}
find_config(path, key, default=None)[source]

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

get_serving(local, remote, scheme, sproto)[source]

Create and return a Request and Response object.

log = None
merge(config)[source]

Merge the given config into self.config.

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

Release the current serving (request and response).

request_class

alias of Request

response_class

alias of Response

root = 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>}
wsgiapp = None
cherrypy.quickstart(root=None, script_name='', config=None)[source]

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.expose(func=None, alias=None)[source]

Expose the function or class.

Optionally provide an alias or set of aliases.

cherrypy.popargs(*args, **kwargs)[source]

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.url(path='', qs='', script_name=None, base=None, relative=None)[source]

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.