cherrypy package¶
Subpackages¶
- cherrypy.lib package
- Submodules
- cherrypy.lib.auth_basic module
- cherrypy.lib.auth_digest module
- cherrypy.lib.caching module
- cherrypy.lib.covercp module
- cherrypy.lib.cpstats module
- cherrypy.lib.cptools module
- cherrypy.lib.encoding module
- cherrypy.lib.gctools module
- cherrypy.lib.httputil module
- cherrypy.lib.jsontools module
- cherrypy.lib.locking module
- cherrypy.lib.profiler module
- cherrypy.lib.reprconf module
- cherrypy.lib.sessions module
- cherrypy.lib.static module
- cherrypy.lib.xmlrpcutil module
- Module contents
- Submodules
- cherrypy.process package
- cherrypy.scaffold package
- cherrypy.test package
- Submodules
- cherrypy.test._test_decorators module
- cherrypy.test._test_states_demo module
- cherrypy.test.benchmark module
- cherrypy.test.checkerdemo module
- cherrypy.test.helper module
- cherrypy.test.logtest module
- cherrypy.test.modfastcgi module
- cherrypy.test.modfcgid module
- cherrypy.test.modpy module
- cherrypy.test.modwsgi module
- cherrypy.test.sessiondemo module
- cherrypy.test.test_auth_basic module
- cherrypy.test.test_auth_digest module
- cherrypy.test.test_bus module
- cherrypy.test.test_caching module
- cherrypy.test.test_config module
- cherrypy.test.test_config_server module
- cherrypy.test.test_conn module
- cherrypy.test.test_core module
- cherrypy.test.test_dynamicobjectmapping module
- cherrypy.test.test_encoding module
- cherrypy.test.test_etags module
- cherrypy.test.test_http module
- cherrypy.test.test_httputil module
- cherrypy.test.test_iterator module
- cherrypy.test.test_json module
- cherrypy.test.test_logging module
- cherrypy.test.test_mime module
- cherrypy.test.test_misc_tools module
- cherrypy.test.test_native module
- cherrypy.test.test_objectmapping module
- cherrypy.test.test_params module
- cherrypy.test.test_plugins module
- cherrypy.test.test_proxy module
- cherrypy.test.test_refleaks module
- cherrypy.test.test_request_obj module
- cherrypy.test.test_routes module
- cherrypy.test.test_session module
- cherrypy.test.test_sessionauthenticate module
- cherrypy.test.test_states module
- cherrypy.test.test_static module
- cherrypy.test.test_tools module
- cherrypy.test.test_tutorials module
- cherrypy.test.test_virtualhost module
- cherrypy.test.test_wsgi_ns module
- cherrypy.test.test_wsgi_unix_socket module
- cherrypy.test.test_wsgi_vhost module
- cherrypy.test.test_wsgiapps module
- cherrypy.test.test_xmlrpc module
- cherrypy.test.webtest module
- Module contents
- Submodules
- cherrypy.tutorial package
- Submodules
- cherrypy.tutorial.tut01_helloworld module
- cherrypy.tutorial.tut02_expose_methods module
- cherrypy.tutorial.tut03_get_and_post module
- cherrypy.tutorial.tut04_complex_site module
- cherrypy.tutorial.tut05_derived_objects module
- cherrypy.tutorial.tut06_default_method module
- cherrypy.tutorial.tut07_sessions module
- cherrypy.tutorial.tut08_generators_and_yield module
- cherrypy.tutorial.tut09_files module
- cherrypy.tutorial.tut10_http_errors module
- Module contents
- Submodules
Submodules¶
- cherrypy.__main__ module
- cherrypy._cpchecker module
- cherrypy._cpcompat module
- cherrypy._cpconfig module
- cherrypy._cpdispatch module
- cherrypy._cperror module
- cherrypy._cplogging module
- cherrypy._cpmodpy module
- cherrypy._cpnative_server module
- cherrypy._cpreqbody module
- cherrypy._cprequest module
- cherrypy._cpserver module
- cherrypy._cptools module
- cherrypy._cptree module
- cherrypy._cpwsgi module
- cherrypy._cpwsgi_server module
- cherrypy._helper module
- cherrypy._json module
- cherrypy.daemon module
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.
-
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
= {}¶ pathconf} pairs, where ‘pathconf’ is itself a dict of {key: value} pairs.
- Type
A dict of {path
-
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¶ A LogManager instance. See _cplogging.
-
namespaces
= {}¶
-
relative_urls
= False¶
-
request_class
¶ alias of
cherrypy._cprequest.Request
-
response_class
¶ alias of
cherrypy._cprequest.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.
-
property
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¶ A CPWSGIApp instance. See _cpwsgi.
-
-
exception
cherrypy.
CherryPyException
[source]¶ Bases:
Exception
A base class for CherryPy exceptions.
-
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 optionalmessage
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.
-
classmethod
handle
(exception, status=500, message='')[source]¶ Translate exception into an HTTPError.
-
reason
= None¶ The HTTP Reason-Phrase string.
-
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¶ The HTTP status code. May be of type int or str (with a Reason-Phrase).
-
-
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 astatus
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.
-
default_status
= 303¶
-
encoding
= 'utf-8'¶ The encoding when passed urls are not native strings
-
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.
-
property
status
¶ The integer HTTP status code to emit.
-
urls
= None¶ The list of URL’s to emit.
-
-
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")
.
-
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.
-
_setup
()[source]¶ Hook this tool into cherrypy.request.
The standard CherryPy request object will automatically call this method when the tool is “turned on” in config.
-
namespace
= 'tools'¶
-
property
on
¶
-
-
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]¶ Decorate _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)[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.
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.