cherrypy._cprequest module

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

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)[source]

Bases: dict

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

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

Append a new Hook made from the supplied arguments.

copy() a shallow copy of D

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

classmethod run_hooks(hooks)[source]

Execute the indicated hooks, trapping errors.

Hooks with .failsafe == True are guaranteed to run even if others at the same hookpoint fail. In this case, log the failure and proceed on to the next hook. The only way to stop all processing from one of these hooks is to raise a BaseException like SystemExit or KeyboardInterrupt and stop the whole server.

class cherrypy._cprequest.LazyUUID4[source]

Bases: object

property uuid4

Provide unique id on per-request basis using UUID4.

It’s evaluated lazily on render.

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

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 = ''

//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.


The (scheme

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).


Run cleanup code.


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 and the final handler, and inherits downward).

cookie = {}

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 See help(cherrypy.dispatch) for more information.

error_page = {}

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.


A dict of {error code


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.


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



Handle the last unanticipated exception.


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, 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': []}

[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


A HookMap (dict-like object) of the form



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

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

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.


Parse HTTP header data into Python structures.



Parse the query string into Python structures.


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 ‘’ 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('', 1111, '')

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.


Generate a response for the resource at self.path_info.


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)[source]

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”).


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.


A list of (name, value) tuples.


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, 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 does not trap.

toolmaps = {}

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

unique_id = None

A lazy object generating and memorizing UUID4 on str() render.

class cherrypy._cprequest.Response[source]

Bases: object

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


Discard self.body but consume any generator such that any finalization can occur, such as is required by caching.tee_output().


The body (entity) of the HTTP response.


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

cookie = {}

See help(Cookie).


Transform headers (and cookies) into self.header_list.


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.

class cherrypy._cprequest.ResponseBody[source]

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)[source]

Attach error pages declared in config.

cherrypy._cprequest.hooks_namespace(k, v)[source]

Attach bare hooks declared in config.

cherrypy._cprequest.request_namespace(k, v)[source]

Attach request attributes declared in config.

cherrypy._cprequest.response_namespace(k, v)[source]

Attach response attributes declared in config.