cherrypy package¶
Subpackages¶
- cherrypy.lib package
- Submodules
- cherrypy.lib.auth module
- 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.http module
- cherrypy.lib.httpauth module
- cherrypy.lib.httputil module
- cherrypy.lib.jsontools module
- cherrypy.lib.lockfile module
- cherrypy.lib.profiler module
- cherrypy.lib.reprconf module
- cherrypy.lib.sessions module
- cherrypy.lib.static module
- cherrypy.lib.xmlrpcutil module
- Module contents
- 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_compat 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_httpauth module
- cherrypy.test.test_httplib 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_objectmapping 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_vhost module
- cherrypy.test.test_wsgiapps module
- cherrypy.test.test_xmlrpc module
- cherrypy.test.webtest module
- Module contents
- 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
- cherrypy.wsgiserver package
Submodules¶
cherrypy._cpchecker module¶
cherrypy._cpcompat module¶
Compatibility code for using CherryPy with various versions of Python.
CherryPy 3.2 is compatible with Python versions 2.6+. 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 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.
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.
escape_html
(s, escape_quote=False)¶ Replace special characters “&”, “<” and “>” to HTML-safe sequences.
When escape_quote=True, escape (‘) and (“) chars.
-
cherrypy._cpcompat.
iteritems
(d)¶
-
cherrypy._cpcompat.
iterkeys
(d)¶
-
cherrypy._cpcompat.
itervalues
(d)¶
-
cherrypy._cpcompat.
json_encode
(value)¶
-
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.
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._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, set with the cherrypy.config
decorator. For example:
@cherrypy.config(**{'tools.gzip.on': True})
class Demo:
@cherrypy.expose
@cherrypy.config(**{'request.show_tracebacks': False})
def index(self):
return "Hello world"
Note
This behavior is only guaranteed for the default dispatcher. Other dispatchers may have different restrictions on where you can attach 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
= {'embedded': {'checker.on': False, 'engine.SIGHUP': None, 'engine.SIGTERM': None, 'engine.autoreload.on': False, 'log.screen': False, 'request.show_mismatched_params': False, 'request.show_tracebacks': False, 'tools.log_headers.on': False}, 'production': {'checker.on': False, 'engine.autoreload.on': False, 'log.screen': False, 'request.show_mismatched_params': False, 'request.show_tracebacks': False, 'tools.log_headers.on': False}, 'staging': {'checker.on': False, 'engine.autoreload.on': False, 'request.show_mismatched_params': False, 'request.show_tracebacks': False, 'tools.log_headers.on': False}, 'test_suite': {'checker.on': False, 'engine.autoreload.on': False, 'log.screen': False, 'request.show_mismatched_params': True, 'request.show_tracebacks': True, '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={33: 95, 34: 95, 35: 95, 36: 95, 37: 95, 38: 95, 39: 95, 40: 95, 41: 95, 42: 95, 43: 95, 44: 95, 45: 95, 46: 95, 47: 95, 58: 95, 59: 95, 60: 95, 61: 95, 62: 95, 63: 95, 64: 95, 91: 95, 92: 95, 93: 95, 94: 95, 95: 95, 96: 95, 123: 95, 124: 95, 125: 95, 126: 95})¶ 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).
-
property
kwargs
¶ page handler kwargs (with cherrypy.request.params copied in)
-
property
-
class
cherrypy._cpdispatch.
MethodDispatcher
(dispatch_method_name=None, translate={33: 95, 34: 95, 35: 95, 36: 95, 37: 95, 38: 95, 39: 95, 40: 95, 41: 95, 42: 95, 43: 95, 44: 95, 45: 95, 46: 95, 47: 95, 58: 95, 59: 95, 60: 95, 61: 95, 62: 95, 63: 95, 64: 95, 91: 95, 92: 95, 93: 95, 94: 95, 95: 95, 96: 95, 123: 95, 124: 95, 125: 95, 126: 95})¶ 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.
-
property
args
¶ The ordered args should be accessible from post dispatch hooks
-
get_args
()¶
-
get_kwargs
()¶
-
property
kwargs
¶ The named kwargs should be accessible from post dispatch hooks
-
set_args
(args)¶
-
set_kwargs
(kwargs)¶
-
property
-
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>, 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>)¶
-
cherrypy._cpdispatch.
getargspec
(callable)¶
-
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
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.
body parameters are also passed as keyword parameters.
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¶

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())
@cherrypy.config(**{'request.error_response': handle_error})
class Root:
pass
Note that you have to explicitly set
response.body
and not simply return an error message as a result.
-
exception
cherrypy._cperror.
CherryPyException
¶ Bases:
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 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.
-
get_error_page
(*args, **kwargs)¶
-
classmethod
handle
(exception, status=500, message='')¶ Translate exception into an HTTPError.
-
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 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.
-
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).
-
property
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} {l} {u} {t} "{r}" {s} {b} "{f}" "{a}"'¶
-
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 tomsg
.
-
property
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.
-
property
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).
-
property
wsgi
¶ Write errors to wsgi.errors.
If you set this to True, it’ll add the appropriate
WSGIErrorHandler
for you (which writes errors towsgi.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
()¶ Acquire a thread lock for serializing access to the underlying I/O.
-
emit
(record)¶ Do whatever it takes to actually log the specified logging record.
This version is intended to be implemented by subclasses and so raises a NotImplementedError.
-
handle
(record)¶ Conditionally emit the specified logging record.
Emission depends on filters which may have been added to the handler. Wrap the actual emission of the record with acquisition/release of the I/O thread lock. Returns whether the filter passed the record for emission.
-
cherrypy._cpmodpy module¶
cherrypy._cpnative_server module¶
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
andbefore_handler
tools, CherryPy tries to process the request body (if any) by callingrequest.body.process
. This uses thecontent_type
of the Entity to look up a suitable processor inEntity.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 thedefault_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 thePart
itself if it’s a file. (In this case it will havefile
andfilename
attributes, or possibly avalue
attribute). Each Part is itself a subclass of Entity, and has its ownprocess
method andprocessors
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.
-
decode_entity
(value)¶ Return a given byte encoded value as a string
-
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 missingContent-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” (seePart
).
-
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 therequest.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
= {'application/x-www-form-urlencoded': <function process_urlencoded>, 'multipart': <function process_multipart>, 'multipart/form-data': <function process_multipart_form_data>}¶ 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)¶
-
property
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 missingContent-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 bymake_file
) instead of a string. Defaults to 1000, just like thecgi
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 missingContent-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” (seePart
).
-
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)¶ Bases:
object
-
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._cpreqbody.
unquote_plus
(bs)¶ Bytes version of urllib.parse.unquote_plus.
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
(points=None)¶ 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
() → a shallow copy of D¶
-
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).
-
property
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).
See help(Cookie).
-
dispatch
= <cherrypy._cpdispatch.Dispatcher object>¶ 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.
-
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
= {'after_error_response': [], 'before_error_response': [], 'before_finalize': [], 'before_handler': [], 'before_request_body': [], 'on_end_request': [], 'on_end_resource': [], 'on_start_resource': []}¶ 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', 'PATCH')¶ 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
= {'error_page': <function error_page_namespace>, 'hooks': <function hooks_namespace>, 'request': <function request_namespace>, 'response': <function response_namespace>, 'tools': <cherrypy._cptools.Toolbox object>}¶
-
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
= (<class 'KeyboardInterrupt'>, <class '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.
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).
-
unicode_err
= 'Page handlers MUST return bytes. Use tools.encode if you wish to return unicode.'¶
-
-
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()
-
accepted_queue_size
= -1¶ The maximum number of requests which will be queued up before the server refuses to accept it (default -1, meaning no limit).
-
accepted_queue_timeout
= 10¶ The timeout in seconds for attempting to add a request to the queue when the queue is full (default 10).
-
base
()¶ Return the base (scheme://host[:port] or sock file) for this server.
-
property
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.
-
property
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
= 'builtin'¶ 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._cpserver.
check_port
(host, port, timeout=1.0)¶ Raise an error if the given port is not free on the given host.
-
cherrypy._cpserver.
client_host
(server_host)¶ Return the host on which a client can connect to the given listener.
-
cherrypy._cpserver.
wait_for_free_port
(host, port, timeout=None)¶ Wait for the specified port to become free (drop requests).
-
cherrypy._cpserver.
wait_for_occupied_port
(host, port, timeout=None)¶ Wait for the specified port to become active (receive requests).
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
(*args, **kwargs)¶
-
-
class
cherrypy._cptools.
SessionAuthTool
(callable, name=None)¶
-
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'¶
-
property
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.
-
register
(point, **kwargs)¶ Return a decorator which registers the function at the given hook point.
-
-
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
= {}¶
-
relative_urls
= False¶
-
release_serving
()¶ Release the current serving (request and response).
-
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.
-
-
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', 'CONTENT_TYPE': 'Content-Type', 'HTTP_CGI_AUTHORIZATION': 'Authorization', 'REMOTE_ADDR': 'Remote-Addr', 'REMOTE_HOST': 'Remote-Host'}¶
-
recode_path_qs
(path, qs)¶
-
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=(<class 'KeyboardInterrupt'>, <class '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.