cherrypy.lib package

Submodules

cherrypy.lib.auth module

cherrypy.lib.auth.basic_auth(realm, users, encrypt=None, debug=False)

If auth fails, raise 401 with a basic authentication header.

realm
A string containing the authentication realm.
users
A dict of the form: {username: password} or a callable returning a dict.
encrypt
callable used to encrypt the password returned from the user-agent. if None it defaults to a md5 encryption.
cherrypy.lib.auth.check_auth(users, encrypt=None, realm=None)

If an authorization header contains credentials, return True or False.

cherrypy.lib.auth.digest_auth(realm, users, debug=False)

If auth fails, raise 401 with a digest authentication header.

realm
A string containing the authentication realm.
users
A dict of the form: {username: password} or a callable returning a dict.

cherrypy.lib.auth_basic module

This module provides a CherryPy 3.x tool which implements the server-side of HTTP Basic Access Authentication, as described in RFC 2617.

Example usage, using the built-in checkpassword_dict function which uses a dict as the credentials store:

userpassdict = {'bird' : 'bebop', 'ornette' : 'wayout'}
checkpassword = cherrypy.lib.auth_basic.checkpassword_dict(userpassdict)
basic_auth = {'tools.auth_basic.on': True,
              'tools.auth_basic.realm': 'earth',
              'tools.auth_basic.checkpassword': checkpassword,
}
app_config = { '/' : basic_auth }
cherrypy.lib.auth_basic.basic_auth(realm, checkpassword, debug=False)

A CherryPy tool which hooks at before_handler to perform HTTP Basic Access Authentication, as specified in RFC 2617.

If the request has an ‘authorization’ header with a ‘Basic’ scheme, this tool attempts to authenticate the credentials supplied in that header. If the request has no ‘authorization’ header, or if it does but the scheme is not ‘Basic’, or if authentication fails, the tool sends a 401 response with a ‘WWW-Authenticate’ Basic header.

realm
A string containing the authentication realm.
checkpassword
A callable which checks the authentication credentials. Its signature is checkpassword(realm, username, password). where username and password are the values obtained from the request’s ‘authorization’ header. If authentication succeeds, checkpassword returns True, else it returns False.
cherrypy.lib.auth_basic.checkpassword_dict(user_password_dict)

Returns a checkpassword function which checks credentials against a dictionary of the form: {username : password}.

If you want a simple dictionary-based authentication scheme, use checkpassword_dict(my_credentials_dict) as the value for the checkpassword argument to basic_auth().

cherrypy.lib.auth_digest module

An implementation of the server-side of HTTP Digest Access Authentication, which is described in RFC 2617.

Example usage, using the built-in get_ha1_dict_plain function which uses a dict of plaintext passwords as the credentials store:

userpassdict = {'alice' : '4x5istwelve'}
get_ha1 = cherrypy.lib.auth_digest.get_ha1_dict_plain(userpassdict)
digest_auth = {'tools.auth_digest.on': True,
               'tools.auth_digest.realm': 'wonderland',
               'tools.auth_digest.get_ha1': get_ha1,
               'tools.auth_digest.key': 'a565c27146791cfb',
}
app_config = { '/' : digest_auth }
cherrypy.lib.auth_digest.H(s)

The hash function H

class cherrypy.lib.auth_digest.HttpDigestAuthorization(auth_header, http_method, debug=False)

Bases: object

Class to parse a Digest Authorization header and perform re-calculation of the digest.

HA2(entity_body='')

Returns the H(A2) string. See RFC 2617 section 3.2.2.3.

errmsg(s)
is_nonce_stale(max_age_seconds=600)

Returns True if a validated nonce is stale. The nonce contains a timestamp in plaintext and also a secure hash of the timestamp. You should first validate the nonce to ensure the plaintext timestamp is not spoofed.

request_digest(ha1, entity_body='')

Calculates the Request-Digest. See RFC 2617 section 3.2.2.1.

ha1
The HA1 string obtained from the credentials store.
entity_body
If ‘qop’ is set to ‘auth-int’, then A2 includes a hash of the “entity body”. The entity body is the part of the message which follows the HTTP headers. See RFC 2617 section 4.3. This refers to the entity the user agent sent in the request which has the Authorization header. Typically GET requests don’t have an entity, and POST requests do.
validate_nonce(s, key)

Validate the nonce. Returns True if nonce was generated by synthesize_nonce() and the timestamp is not spoofed, else returns False.

s
A string related to the resource, such as the hostname of the server.
key
A secret string known only to the server.

Both s and key must be the same values which were used to synthesize the nonce we are trying to validate.

cherrypy.lib.auth_digest.TRACE(msg)
cherrypy.lib.auth_digest.digest_auth(realm, get_ha1, key, debug=False)

A CherryPy tool which hooks at before_handler to perform HTTP Digest Access Authentication, as specified in RFC 2617.

If the request has an ‘authorization’ header with a ‘Digest’ scheme, this tool authenticates the credentials supplied in that header. If the request has no ‘authorization’ header, or if it does but the scheme is not “Digest”, or if authentication fails, the tool sends a 401 response with a ‘WWW-Authenticate’ Digest header.

realm
A string containing the authentication realm.
get_ha1
A callable which looks up a username in a credentials store and returns the HA1 string, which is defined in the RFC to be MD5(username : realm : password). The function’s signature is: get_ha1(realm, username) where username is obtained from the request’s ‘authorization’ header. If username is not found in the credentials store, get_ha1() returns None.
key
A secret string known only to the server, used in the synthesis of nonces.
cherrypy.lib.auth_digest.get_ha1_dict(user_ha1_dict)

Returns a get_ha1 function which obtains a HA1 password hash from a dictionary of the form: {username : HA1}.

If you want a dictionary-based authentication scheme, but with pre-computed HA1 hashes instead of plain-text passwords, use get_ha1_dict(my_userha1_dict) as the value for the get_ha1 argument to digest_auth().

cherrypy.lib.auth_digest.get_ha1_dict_plain(user_password_dict)

Returns a get_ha1 function which obtains a plaintext password from a dictionary of the form: {username : password}.

If you want a simple dictionary-based authentication scheme, with plaintext passwords, use get_ha1_dict_plain(my_userpass_dict) as the value for the get_ha1 argument to digest_auth().

cherrypy.lib.auth_digest.get_ha1_file_htdigest(filename)

Returns a get_ha1 function which obtains a HA1 password hash from a flat file with lines of the same format as that produced by the Apache htdigest utility. For example, for realm ‘wonderland’, username ‘alice’, and password ‘4x5istwelve’, the htdigest line would be:

alice:wonderland:3238cdfe91a8b2ed8e39646921a02d4c

If you want to use an Apache htdigest file as the credentials store, then use get_ha1_file_htdigest(my_htdigest_file) as the value for the get_ha1 argument to digest_auth(). It is recommended that the filename argument be an absolute path, to avoid problems.

cherrypy.lib.auth_digest.md5_hex(s)
cherrypy.lib.auth_digest.synthesize_nonce(s, key, timestamp=None)

Synthesize a nonce value which resists spoofing and can be checked for staleness. Returns a string suitable as the value for ‘nonce’ in the www-authenticate header.

s
A string related to the resource, such as the hostname of the server.
key
A secret string known only to the server.
timestamp
An integer seconds-since-the-epoch timestamp
cherrypy.lib.auth_digest.www_authenticate(realm, key, algorithm='MD5', nonce=None, qop='auth', stale=False)

Constructs a WWW-Authenticate header for Digest authentication.

cherrypy.lib.caching module

CherryPy implements a simple caching system as a pluggable Tool. This tool tries to be an (in-process) HTTP/1.1-compliant cache. It’s not quite there yet, but it’s probably good enough for most sites.

In general, GET responses are cached (along with selecting headers) and, if another request arrives for the same resource, the caching Tool will return 304 Not Modified if possible, or serve the cached response otherwise. It also sets request.cached to True if serving a cached representation, and sets request.cacheable to False (so it doesn’t get cached again).

If POST, PUT, or DELETE requests are made for a cached resource, they invalidate (delete) any cached response.

Usage

Configuration file example:

[/]
tools.caching.on = True
tools.caching.delay = 3600

You may use a class other than the default MemoryCache by supplying the config entry cache_class; supply the full dotted name of the replacement class as the config value. It must implement the basic methods get, put, delete, and clear.

You may set any attribute, including overriding methods, on the cache instance by providing them in config. The above sets the delay attribute, for example.

class cherrypy.lib.caching.AntiStampedeCache

Bases: dict

A storage system for cached items which reduces stampede collisions.

wait(key, timeout=5, debug=False)

Return the cached value for the given key, or None.

If timeout is not None, and the value is already being calculated by another thread, wait until the given timeout has elapsed. If the value is available before the timeout expires, it is returned. If not, None is returned, and a sentinel placed in the cache to signal other threads to wait.

If timeout is None, no waiting is performed nor sentinels used.

class cherrypy.lib.caching.Cache

Bases: object

Base class for Cache implementations.

clear()

Reset the cache to its initial, empty state.

delete()

Remove ALL cached variants of the current resource.

get()

Return the current variant if in the cache, else None.

put(obj, size)

Store the current variant in the cache.

class cherrypy.lib.caching.MemoryCache

Bases: cherrypy.lib.caching.Cache

An in-memory cache for varying response content.

Each key in self.store is a URI, and each value is an AntiStampedeCache. The response for any given URI may vary based on the values of “selecting request headers”; that is, those named in the Vary response header. We assume the list of header names to be constant for each URI throughout the lifetime of the application, and store that list in self.store[uri].selecting_headers.

The items contained in self.store[uri] have keys which are tuples of request header values (in the same order as the names in its selecting_headers), and values which are the actual responses.

antistampede_timeout = 5

Seconds to wait for other threads to release a cache lock.

clear()

Reset the cache to its initial, empty state.

debug = False
delay = 600

Seconds until the cached content expires; defaults to 600 (10 minutes).

delete()

Remove ALL cached variants of the current resource.

expire_cache()

Continuously examine cached objects, expiring stale ones.

This function is designed to be run in its own daemon thread, referenced at self.expiration_thread.

expire_freq = 0.1

Seconds to sleep between cache expiration sweeps.

get()

Return the current variant if in the cache, else None.

maxobj_size = 100000

The maximum size of each cached object in bytes; defaults to 100 KB.

maxobjects = 1000

The maximum number of cached objects; defaults to 1000.

maxsize = 10000000

The maximum size of the entire cache in bytes; defaults to 10 MB.

put(variant, size)

Store the current variant in the cache.

cherrypy.lib.caching.expires(secs=0, force=False, debug=False)

Tool for influencing cache mechanisms using the ‘Expires’ header.

secs

Must be either an int or a datetime.timedelta, and indicates the number of seconds between response.time and when the response should expire. The ‘Expires’ header will be set to response.time + secs. If secs is zero, the ‘Expires’ header is set one year in the past, and the following “cache prevention” headers are also set:

  • Pragma: no-cache
  • Cache-Control’: no-cache, must-revalidate
force

If False, the following headers are checked:

  • Etag
  • Last-Modified
  • Age
  • Expires

If any are already present, none of the above response headers are set.

cherrypy.lib.caching.get(invalid_methods=('POST', 'PUT', 'DELETE'), debug=False, **kwargs)

Try to obtain cached output. If fresh enough, raise HTTPError(304).

If POST, PUT, or DELETE:
  • invalidates (deletes) any cached response for this resource
  • sets request.cached = False
  • sets request.cacheable = False
else if a cached copy exists:
  • sets request.cached = True
  • sets request.cacheable = False
  • sets response.headers to the cached values
  • checks the cached Last-Modified response header against the current If-(Un)Modified-Since request headers; raises 304 if necessary.
  • sets response.status and response.body to the cached values
  • returns True
otherwise:
  • sets request.cached = False
  • sets request.cacheable = True
  • returns False
cherrypy.lib.caching.tee_output()

Tee response output to cache storage. Internal.

cherrypy.lib.covercp module

Code-coverage tools for CherryPy.

To use this module, or the coverage tools in the test suite, you need to download ‘coverage.py’, either Gareth Rees’ original implementation or Ned Batchelder’s enhanced version:

To turn on coverage tracing, use the following code:

cherrypy.engine.subscribe('start', covercp.start)

DO NOT subscribe anything on the ‘start_thread’ channel, as previously recommended. Calling start once in the main thread should be sufficient to start coverage on all threads. Calling start again in each thread effectively clears any coverage data gathered up to that point.

Run your code, then use the covercp.serve() function to browse the results in a web browser. If you run this module from the command line, it will call serve() for you.

class cherrypy.lib.covercp.CoverStats(coverage, root=None)

Bases: object

annotated_file(filename, statements, excluded, missing)
index()
menu(base='/', pct='50', showpct='', exclude='python\\d\\.\\d|test|tut\\d|tutorial')
report(name)
cherrypy.lib.covercp.get_tree(base, exclude, coverage=None)

Return covered module names as a nested dict.

cherrypy.lib.covercp.serve(path='/home/docs/checkouts/readthedocs.org/user_builds/cherrypy-wolph/envs/v9.0.0/lib/python3.4/site-packages/CherryPy-9.0.0-py3.4.egg/cherrypy/lib/coverage.cache', port=8080, root=None)
cherrypy.lib.covercp.start()

cherrypy.lib.cpstats module

CPStats, a package for collecting and reporting on program statistics.

Overview

Statistics about program operation are an invaluable monitoring and debugging tool. Unfortunately, the gathering and reporting of these critical values is usually ad-hoc. This package aims to add a centralized place for gathering statistical performance data, a structure for recording that data which provides for extrapolation of that data into more useful information, and a method of serving that data to both human investigators and monitoring software. Let’s examine each of those in more detail.

Data Gathering

Just as Python’s logging module provides a common importable for gathering and sending messages, performance statistics would benefit from a similar common mechanism, and one that does not require each package which wishes to collect stats to import a third-party module. Therefore, we choose to re-use the logging module by adding a statistics object to it.

That logging.statistics object is a nested dict. It is not a custom class, because that would:

  1. require libraries and applications to import a third-party module in order to participate
  2. inhibit innovation in extrapolation approaches and in reporting tools, and
  3. be slow.

There are, however, some specifications regarding the structure of the dict.:

{
  +----"SQLAlchemy": {
  |        "Inserts": 4389745,
  |        "Inserts per Second":
  |            lambda s: s["Inserts"] / (time() - s["Start"]),
  |  C +---"Table Statistics": {
  |  o |        "widgets": {-----------+
N |  l |            "Rows": 1.3M,      | Record
a |  l |            "Inserts": 400,    |
m |  e |        },---------------------+
e |  c |        "froobles": {
s |  t |            "Rows": 7845,
p |  i |            "Inserts": 0,
a |  o |        },
c |  n +---},
e |        "Slow Queries":
  |            [{"Query": "SELECT * FROM widgets;",
  |              "Processing Time": 47.840923343,
  |              },
  |             ],
  +----},
}

The logging.statistics dict has four levels. The topmost level is nothing more than a set of names to introduce modularity, usually along the lines of package names. If the SQLAlchemy project wanted to participate, for example, it might populate the item logging.statistics[‘SQLAlchemy’], whose value would be a second-layer dict we call a “namespace”. Namespaces help multiple packages to avoid collisions over key names, and make reports easier to read, to boot. The maintainers of SQLAlchemy should feel free to use more than one namespace if needed (such as ‘SQLAlchemy ORM’). Note that there are no case or other syntax constraints on the namespace names; they should be chosen to be maximally readable by humans (neither too short nor too long).

Each namespace, then, is a dict of named statistical values, such as ‘Requests/sec’ or ‘Uptime’. You should choose names which will look good on a report: spaces and capitalization are just fine.

In addition to scalars, values in a namespace MAY be a (third-layer) dict, or a list, called a “collection”. For example, the CherryPy StatsTool keeps track of what each request is doing (or has most recently done) in a ‘Requests’ collection, where each key is a thread ID; each value in the subdict MUST be a fourth dict (whew!) of statistical data about each thread. We call each subdict in the collection a “record”. Similarly, the StatsTool also keeps a list of slow queries, where each record contains data about each slow query, in order.

Values in a namespace or record may also be functions, which brings us to:

Extrapolation

The collection of statistical data needs to be fast, as close to unnoticeable as possible to the host program. That requires us to minimize I/O, for example, but in Python it also means we need to minimize function calls. So when you are designing your namespace and record values, try to insert the most basic scalar values you already have on hand.

When it comes time to report on the gathered data, however, we usually have much more freedom in what we can calculate. Therefore, whenever reporting tools (like the provided StatsPage CherryPy class) fetch the contents of logging.statistics for reporting, they first call extrapolate_statistics (passing the whole statistics dict as the only argument). This makes a deep copy of the statistics dict so that the reporting tool can both iterate over it and even change it without harming the original. But it also expands any functions in the dict by calling them. For example, you might have a ‘Current Time’ entry in the namespace with the value “lambda scope: time.time()”. The “scope” parameter is the current namespace dict (or record, if we’re currently expanding one of those instead), allowing you access to existing static entries. If you’re truly evil, you can even modify more than one entry at a time.

However, don’t try to calculate an entry and then use its value in further extrapolations; the order in which the functions are called is not guaranteed. This can lead to a certain amount of duplicated work (or a redesign of your schema), but that’s better than complicating the spec.

After the whole thing has been extrapolated, it’s time for:

Reporting

The StatsPage class grabs the logging.statistics dict, extrapolates it all, and then transforms it to HTML for easy viewing. Each namespace gets its own header and attribute table, plus an extra table for each collection. This is NOT part of the statistics specification; other tools can format how they like.

You can control which columns are output and how they are formatted by updating StatsPage.formatting, which is a dict that mirrors the keys and nesting of logging.statistics. The difference is that, instead of data values, it has formatting values. Use None for a given key to indicate to the StatsPage that a given column should not be output. Use a string with formatting (such as ‘%.3f’) to interpolate the value(s), or use a callable (such as lambda v: v.isoformat()) for more advanced formatting. Any entry which is not mentioned in the formatting dict is output unchanged.

Monitoring

Although the HTML output takes pains to assign unique id’s to each <td> with statistical data, you’re probably better off fetching /cpstats/data, which outputs the whole (extrapolated) logging.statistics dict in JSON format. That is probably easier to parse, and doesn’t have any formatting controls, so you get the “original” data in a consistently-serialized format. Note: there’s no treatment yet for datetime objects. Try time.time() instead for now if you can. Nagios will probably thank you.

Turning Collection Off

It is recommended each namespace have an “Enabled” item which, if False, stops collection (but not reporting) of statistical data. Applications SHOULD provide controls to pause and resume collection by setting these entries to False or True, if present.

Usage

To collect statistics on CherryPy applications:

from cherrypy.lib import cpstats
appconfig['/']['tools.cpstats.on'] = True

To collect statistics on your own code:

import logging
# Initialize the repository
if not hasattr(logging, 'statistics'): logging.statistics = {}
# Initialize my namespace
mystats = logging.statistics.setdefault('My Stuff', {})
# Initialize my namespace's scalars and collections
mystats.update({
    'Enabled': True,
    'Start Time': time.time(),
    'Important Events': 0,
    'Events/Second': lambda s: (
        (s['Important Events'] / (time.time() - s['Start Time']))),
    })
...
for event in events:
    ...
    # Collect stats
    if mystats.get('Enabled', False):
        mystats['Important Events'] += 1

To report statistics:

root.cpstats = cpstats.StatsPage()

To format statistics reports:

See 'Reporting', above.
class cherrypy.lib.cpstats.ByteCountWrapper(rfile)

Bases: object

Wraps a file-like object, counting the number of bytes read.

close()
next()
read(size=-1)
readline(size=-1)
readlines(sizehint=0)
class cherrypy.lib.cpstats.StatsPage

Bases: object

data()
formatting = {'CherryPy Applications': {'Total Time': '%.3f', 'Requests/Second': '%.3f', 'Bytes Read/Second': '%.3f', 'Bytes Read/Request': '%.3f', 'Start Time': <function <lambda> at 0x7fee87cd9950>, 'Requests': {'Bytes Written': '%s', 'Processing Time': '%.3f', 'Start Time': None, 'Bytes Read': '%s', 'End Time': None}, 'Slow Queries': {'Start Time': <function <lambda> at 0x7fee87cd9950>, 'Processing Time': '%.3f', 'End Time': None}, 'URI Set Tracking': {'Sum': '%.3f', 'Min': '%.3f', 'Max': '%.3f', 'Avg': '%.3f'}, 'Bytes Written/Second': '%.3f', 'Uptime': '%.3f', 'Bytes Written/Request': '%.3f', 'Enabled': <function pause_resume.<locals>._pause_resume at 0x7fee87cd9730>, 'Current Time': <function <lambda> at 0x7fee87cd9950>}, 'CherryPy WSGIServer': {'Enabled': <function pause_resume.<locals>._pause_resume at 0x7fee87cd97b8>, 'Start time': <function <lambda> at 0x7fee87cd9950>, 'Connections/second': '%.3f'}}
get_dict_collection(v, formatting)

Return ([headers], [rows]) for the given collection.

get_list_collection(v, formatting)

Return ([headers], [subrows]) for the given collection.

get_namespaces()

Yield (title, scalars, collections) for each namespace.

index()
pause(namespace)
resume(namespace)
class cherrypy.lib.cpstats.StatsTool

Bases: cherrypy._cptools.Tool

Record various information about the current request.

record_start()

Record the beginning of a request.

record_stop(uriset=None, slow_queries=1.0, slow_queries_count=100, debug=False, **kwargs)

Record the end of a request.

cherrypy.lib.cpstats.average_uriset_time(s)
cherrypy.lib.cpstats.extrapolate_statistics(scope)

Return an extrapolated copy of the given scope.

cherrypy.lib.cpstats.iso_format(v)
cherrypy.lib.cpstats.locale_date(v)
cherrypy.lib.cpstats.pause_resume(ns)
cherrypy.lib.cpstats.proc_time(s)

cherrypy.lib.cptools module

Functions for builtin CherryPy tools.

class cherrypy.lib.cptools.MonitoredHeaderMap

Bases: cherrypy.lib.httputil.HeaderMap

get(key, default=None)
class cherrypy.lib.cptools.SessionAuth

Bases: object

Assert that the user is logged in.

anonymous()

Provide a temporary user name for anonymous users.

check_username_and_password(username, password)
debug = False
do_check()

Assert username. Raise redirect, or return True if request handled.

do_login(username, password, from_page='..', **kwargs)

Login. May raise redirect, or return True if request handled.

do_logout(from_page='..', **kwargs)

Logout. May raise redirect, or return True if request handled.

login_screen(from_page='..', username='', error_msg='', **kwargs)
on_check(username)
on_login(username)
on_logout(username)
run()
session_key = 'username'
cherrypy.lib.cptools.accept(media=None, debug=False)

Return the client’s preferred media-type (from the given Content-Types).

If ‘media’ is None (the default), no test will be performed.

If ‘media’ is provided, it should be the Content-Type value (as a string) or values (as a list or tuple of strings) which the current resource can emit. The client’s acceptable media ranges (as declared in the Accept request header) will be matched in order to these Content-Type values; the first such string is returned. That is, the return value will always be one of the strings provided in the ‘media’ arg (or None if ‘media’ is None).

If no match is found, then HTTPError 406 (Not Acceptable) is raised. Note that most web browsers send / as a (low-quality) acceptable media range, which should match any Content-Type. In addition, ”...if no Accept header field is present, then it is assumed that the client accepts all media types.”

Matching types are checked in order of client preference first, and then in the order of the given ‘media’ values.

Note that this function does not honor accept-params (other than “q”).

cherrypy.lib.cptools.allow(methods=None, debug=False)

Raise 405 if request.method not in methods (default [‘GET’, ‘HEAD’]).

The given methods are case-insensitive, and may be in any order. If only one method is allowed, you may supply a single string; if more than one, supply a list of strings.

Regardless of whether the current method is allowed or not, this also emits an ‘Allow’ response header, containing the given methods.

cherrypy.lib.cptools.autovary(ignore=None, debug=False)

Auto-populate the Vary response header based on request.header access.

cherrypy.lib.cptools.convert_params(exception=<class 'ValueError'>, error=400)

Convert request params based on function annotations, with error handling.

exception
Exception class to catch.
status
The HTTP error code to return to the client on failure.
cherrypy.lib.cptools.flatten(debug=False)

Wrap response.body in a generator that recursively iterates over body.

This allows cherrypy.response.body to consist of ‘nested generators’; that is, a set of generators that yield generators.

cherrypy.lib.cptools.ignore_headers(headers=('Range', ), debug=False)

Delete request headers whose field names are included in ‘headers’.

This is a useful tool for working behind certain HTTP servers; for example, Apache duplicates the work that CP does for ‘Range’ headers, and will doubly-truncate the response.

cherrypy.lib.cptools.log_hooks(debug=False)

Write request.hooks to the cherrypy error log.

cherrypy.lib.cptools.log_request_headers(debug=False)

Write request headers to the cherrypy error log.

cherrypy.lib.cptools.log_traceback(severity=40, debug=False)

Write the last error’s traceback to the cherrypy error log.

cherrypy.lib.cptools.proxy(base=None, local='X-Forwarded-Host', remote='X-Forwarded-For', scheme='X-Forwarded-Proto', debug=False)

Change the base URL (scheme://host[:port][/path]).

For running a CP server behind Apache, lighttpd, or other HTTP server.

For Apache and lighttpd, you should leave the ‘local’ argument at the default value of ‘X-Forwarded-Host’. For Squid, you probably want to set tools.proxy.local = ‘Origin’.

If you want the new request.base to include path info (not just the host), you must explicitly set base to the full base path, and ALSO set ‘local’ to ‘’, so that the X-Forwarded-Host request header (which never includes path info) does not override it. Regardless, the value for ‘base’ MUST NOT end in a slash.

cherrypy.request.remote.ip (the IP address of the client) will be rewritten if the header specified by the ‘remote’ arg is valid. By default, ‘remote’ is set to ‘X-Forwarded-For’. If you do not want to rewrite remote.ip, set the ‘remote’ arg to an empty string.

cherrypy.lib.cptools.redirect(url='', internal=True, debug=False)

Raise InternalRedirect or HTTPRedirect to the given url.

cherrypy.lib.cptools.referer(pattern, accept=True, accept_missing=False, error=403, message='Forbidden Referer header.', debug=False)

Raise HTTPError if Referer header does/does not match the given pattern.

pattern
A regular expression pattern to test against the Referer.
accept
If True, the Referer must match the pattern; if False, the Referer must NOT match the pattern.
accept_missing
If True, permit requests with no Referer header.
error
The HTTP error code to return to the client on failure.
message
A string to include in the response body on failure.
cherrypy.lib.cptools.response_headers(headers=None, debug=False)

Set headers on the response.

cherrypy.lib.cptools.session_auth(**kwargs)

Session authentication hook.

Any attribute of the SessionAuth class may be overridden via a keyword arg to this function:

_debug_message: function anonymous: function check_username_and_password: function debug: bool do_check: function do_login: function do_logout: function login_screen: function on_check: function on_login: function on_logout: function run: function session_key: str

cherrypy.lib.cptools.trailing_slash(missing=True, extra=False, status=None, debug=False)

Redirect if path_info has (missing|extra) trailing slash.

cherrypy.lib.cptools.validate_etags(autotags=False, debug=False)

Validate the current ETag against If-Match, If-None-Match headers.

If autotags is True, an ETag response-header value will be provided from an MD5 hash of the response body (unless some other code has already provided an ETag header). If False (the default), the ETag will not be automatic.

WARNING: the autotags feature is not designed for URL’s which allow methods other than GET. For example, if a POST to the same URL returns no content, the automatic ETag will be incorrect, breaking a fundamental use for entity tags in a possibly destructive fashion. Likewise, if you raise 304 Not Modified, the response body will be empty, the ETag hash will be incorrect, and your application will break. See RFC 2616 Section 14.24.

cherrypy.lib.cptools.validate_since()

Validate the current Last-Modified against If-Modified-Since headers.

If no code has set the Last-Modified response header, then no validation will be performed.

cherrypy.lib.encoding module

class cherrypy.lib.encoding.ResponseEncoder(**kwargs)

Bases: object

add_charset = True
debug = False
default_encoding = 'utf-8'
encode_stream(encoding)

Encode a streaming response body.

Use a generator wrapper, and just pray it works as the stream is being written out.

encode_string(encoding)

Encode a buffered response body.

encoding = None
errors = 'strict'
failmsg = 'Response body could not be encoded with %r.'
find_acceptable_charset()
text_only = True
class cherrypy.lib.encoding.UTF8StreamEncoder(iterator)

Bases: object

close()
next()
cherrypy.lib.encoding.compress(body, compress_level)

Compress ‘body’ at the given compress_level.

cherrypy.lib.encoding.decode(encoding=None, default_encoding='utf-8')

Replace or extend the list of charsets used to decode a request entity.

Either argument may be a single string or a list of strings.

encoding
If not None, restricts the set of charsets attempted while decoding a request entity to the given set (even if a different charset is given in the Content-Type request header).
default_encoding
Only in effect if the ‘encoding’ argument is not given. If given, the set of charsets attempted while decoding a request entity is extended with the given value(s).
cherrypy.lib.encoding.decompress(body)
cherrypy.lib.encoding.gzip(compress_level=5, mime_types=['text/html', 'text/plain'], debug=False)

Try to gzip the response body if Content-Type in mime_types.

cherrypy.response.headers[‘Content-Type’] must be set to one of the values in the mime_types arg before calling this function.

The provided list of mime-types must be of one of the following form:
  • type/subtype
  • type/*
  • type/*+subtype
No compression is performed if any of the following hold:
  • The client sends no Accept-Encoding request header
  • No ‘gzip’ or ‘x-gzip’ is present in the Accept-Encoding header
  • No ‘gzip’ or ‘x-gzip’ with a qvalue > 0 is present
  • The ‘identity’ value is given with a qvalue > 0.

cherrypy.lib.gctools module

class cherrypy.lib.gctools.GCRoot

Bases: object

A CherryPy page handler for testing reference leaks.

classes = [(<class 'cherrypy._cprequest.Request'>, 2, 2, 'Should be 1 in this request thread and 1 in the main thread.'), (<class 'cherrypy._cprequest.Response'>, 2, 2, 'Should be 1 in this request thread and 1 in the main thread.'), (<class 'cherrypy._cpwsgi.AppResponse'>, 1, 1, 'Should be 1 in this request thread only.')]
index()
stats()
class cherrypy.lib.gctools.ReferrerTree(ignore=None, maxdepth=2, maxparents=10)

Bases: object

An object which gathers all referrers of an object to a given depth.

ascend(obj, depth=1)

Return a nested list containing referrers of the given object.

format(tree)

Return a list of string reprs from a nested list of referrers.

peek(s)

Return s, restricted to a sane length.

peek_length = 40
class cherrypy.lib.gctools.RequestCounter(bus)

Bases: cherrypy.process.plugins.SimplePlugin

after_request()
before_request()
start()
cherrypy.lib.gctools.get_context(obj)
cherrypy.lib.gctools.get_instances(cls)

cherrypy.lib.httpauth module

This module defines functions to implement HTTP Digest Authentication (RFC 2617). This has full compliance with ‘Digest’ and ‘Basic’ authentication methods. In ‘Digest’ it supports both MD5 and MD5-sess algorithms.

Usage:

First use ‘doAuth’ to request the client authentication for a certain resource. You should send an httplib.UNAUTHORIZED response to the client so he knows he has to authenticate itself.

Then use ‘parseAuthorization’ to retrieve the ‘auth_map’ used in ‘checkResponse’.

To use ‘checkResponse’ you must have already verified the password associated with the ‘username’ key in ‘auth_map’ dict. Then you use the ‘checkResponse’ function to verify if the password matches the one sent by the client.

SUPPORTED_ALGORITHM - list of supported ‘Digest’ algorithms SUPPORTED_QOP - list of supported ‘Digest’ ‘qop’.

cherrypy.lib.httpauth.digestAuth(realm, algorithm='MD5', nonce=None, qop='auth')

Challenges the client for a Digest authentication.

cherrypy.lib.httpauth.basicAuth(realm)

Challengenes the client for a Basic authentication.

cherrypy.lib.httpauth.doAuth(realm)

‘doAuth’ function returns the challenge string b giving priority over Digest and fallback to Basic authentication when the browser doesn’t support the first one.

This should be set in the HTTP header under the key ‘WWW-Authenticate’.

cherrypy.lib.httpauth.checkResponse(auth_map, password, method='GET', encrypt=None, **kwargs)

‘checkResponse’ compares the auth_map with the password and optionally other arguments that each implementation might need.

If the response is of type ‘Basic’ then the function has the following signature:

checkBasicResponse(auth_map, password) -> bool

If the response is of type ‘Digest’ then the function has the following signature:

checkDigestResponse(auth_map, password, method='GET', A1=None) -> bool

The ‘A1’ argument is only used in MD5_SESS algorithm based responses. Check md5SessionKey() for more info.

cherrypy.lib.httpauth.parseAuthorization(credentials)

parseAuthorization will convert the value of the ‘Authorization’ key in the HTTP header to a map itself. If the parsing fails ‘None’ is returned.

cherrypy.lib.httpauth.md5SessionKey(params, password)

If the “algorithm” directive’s value is “MD5-sess”, then A1 [the session key] is calculated only once - on the first request by the client following receipt of a WWW-Authenticate challenge from the server.

This creates a ‘session key’ for the authentication of subsequent requests and responses which is different for each “authentication session”, thus limiting the amount of material hashed with any one key.

Because the server need only use the hash of the user credentials in order to create the A1 value, this construction could be used in conjunction with a third party authentication service so that the web server would not need the actual password value. The specification of such a protocol is beyond the scope of this specification.

cherrypy.lib.httpauth.calculateNonce(realm, algorithm='MD5')

This is an auxaliary function that calculates ‘nonce’ value. It is used to handle sessions.

cherrypy.lib.httputil module

HTTP library functions.

This module contains functions for building an HTTP application framework: any one, not just one whose name starts with “Ch”. ;) If you reference any modules from some popular framework inside this module, FuManChu will personally hang you up by your thumbs and submit you to a public caning.

class cherrypy.lib.httputil.AcceptElement(value, params=None)

Bases: cherrypy.lib.httputil.HeaderElement

An element (with parameters) from an Accept* header’s element list.

AcceptElement objects are comparable; the more-preferred object will be “less than” the less-preferred object. They are also therefore sortable; if you sort a list of AcceptElement objects, they will be listed in priority order; the most preferred value will be first. Yes, it should have been the other way around, but it’s too late to fix now.

classmethod from_str(elementstr)
qvalue

The qvalue, or priority, of this value.

class cherrypy.lib.httputil.CaseInsensitiveDict

Bases: dict

A case-insensitive dict subclass.

Each key is changed on entry to str(key).title().

classmethod fromkeys(seq, value=None)
get(key, default=None)
pop(key, default)
setdefault(key, x=None)
update(E)
class cherrypy.lib.httputil.HeaderElement(value, params=None)

Bases: object

An element (with parameters) from an HTTP header’s element list.

classmethod from_str(elementstr)

Construct an instance from a string of the form ‘token;key=val’.

static parse(elementstr)

Transform ‘token;key=val’ to (‘token’, {‘key’: ‘val’}).

class cherrypy.lib.httputil.HeaderMap

Bases: cherrypy.lib.httputil.CaseInsensitiveDict

A dict subclass for HTTP request and response headers.

Each key is changed on entry to str(key).title(). This allows headers to be case-insensitive and avoid duplicates.

Values are header values (decoded according to RFC 2047 if necessary).

elements(key)

Return a sorted list of HeaderElements for the given header.

classmethod encode(v)

Return the given header name or value, encoded for HTTP output.

classmethod encode_header_items(header_items)

Prepare the sequence of name, value tuples into a form suitable for transmitting on the wire for HTTP.

encodings = ['ISO-8859-1']
output()

Transform self into a list of (name, value) tuples.

protocol = (1, 1)
use_rfc_2047 = True
values(key)

Return a sorted list of HeaderElement.value for the given header.

class cherrypy.lib.httputil.Host(ip, port, name=None)

Bases: object

An internet address.

name
Should be the client’s host name. If not available (because no DNS lookup is performed), the IP address should be used instead.
ip = '0.0.0.0'
name = 'unknown.tld'
port = 80
cherrypy.lib.httputil.decode_TEXT(value)

Decode RFC 2047 TEXT (e.g. “=?utf-8?q?f=C3=BCr?=” -> “fxfcr”).

cherrypy.lib.httputil.get_ranges(headervalue, content_length)

Return a list of (start, stop) indices from a Range header, or None.

Each (start, stop) tuple will be composed of two ints, which are suitable for use in a slicing operation. That is, the header “Range: bytes=3-6”, if applied against a Python string, is requesting resource[3:7]. This function will return the list [(3, 7)].

If this function returns an empty list, you should return HTTP 416.

cherrypy.lib.httputil.header_elements(fieldname, fieldvalue)

Return a sorted HeaderElement list from a comma-separated header string.

cherrypy.lib.httputil.parse_query_string(query_string, keep_blank_values=True, encoding='utf-8')

Build a params dictionary from a query_string.

Duplicate key/value pairs in the provided query_string will be returned as {‘key’: [val1, val2, ...]}. Single key/values will be returned as strings: {‘key’: ‘value’}.

cherrypy.lib.httputil.protocol_from_http(protocol_str)

Return a protocol tuple from the given ‘HTTP/x.y’ string.

cherrypy.lib.httputil.urljoin(*atoms)

Return the given path *atoms, joined into a single URL.

This will correctly join a SCRIPT_NAME and PATH_INFO into the original URL, even if either atom is blank.

cherrypy.lib.httputil.urljoin_bytes(*atoms)

Return the given path *atoms, joined into a single URL.

This will correctly join a SCRIPT_NAME and PATH_INFO into the original URL, even if either atom is blank.

cherrypy.lib.httputil.valid_status(status)

Return legal HTTP status Code, Reason-phrase and Message.

The status arg must be an int, or a str that begins with an int.

If status is an int, or a str and no reason-phrase is supplied, a default reason-phrase will be provided.

cherrypy.lib.jsontools module

cherrypy.lib.jsontools.json_handler(*args, **kwargs)
cherrypy.lib.jsontools.json_in(content_type=['application/json', 'text/javascript'], force=True, debug=False, processor=<function json_processor>)

Add a processor to parse JSON request entities: The default processor places the parsed data into request.json.

Incoming request entities which match the given content_type(s) will be deserialized from JSON to the Python equivalent, and the result stored at cherrypy.request.json. The ‘content_type’ argument may be a Content-Type string or a list of allowable Content-Type strings.

If the ‘force’ argument is True (the default), then entities of other content types will not be allowed; “415 Unsupported Media Type” is raised instead.

Supply your own processor to use a custom decoder, or to handle the parsed data differently. The processor can be configured via tools.json_in.processor or via the decorator method.

Note that the deserializer requires the client send a Content-Length request header, or it will raise “411 Length Required”. If for any other reason the request entity cannot be deserialized from JSON, it will raise “400 Bad Request: Invalid JSON document”.

You must be using Python 2.6 or greater, or have the ‘simplejson’ package importable; otherwise, ValueError is raised during processing.

cherrypy.lib.jsontools.json_out(content_type='application/json', debug=False, handler=<function json_handler>)

Wrap request.handler to serialize its output to JSON. Sets Content-Type.

If the given content_type is None, the Content-Type response header is not set.

Provide your own handler to use a custom encoder. For example cherrypy.config[‘tools.json_out.handler’] = <function>, or @json_out(handler=function).

You must be using Python 2.6 or greater, or have the ‘simplejson’ package importable; otherwise, ValueError is raised during processing.

cherrypy.lib.jsontools.json_processor(entity)

Read application/json data into request.json.

cherrypy.lib.lockfile module

Platform-independent file locking. Inspired by and modeled after zc.lockfile.

exception cherrypy.lib.lockfile.LockError(path)

Bases: Exception

Could not obtain a lock

msg = 'Unable to lock %r'
cherrypy.lib.lockfile.LockFile

alias of UnixLockFile

class cherrypy.lib.lockfile.SystemLockFile(path)

Bases: object

An abstract base class for platform-specific locking.

release()
remove()

Attempt to remove the file

class cherrypy.lib.lockfile.UnixLockFile(path)

Bases: cherrypy.lib.lockfile.SystemLockFile

exception cherrypy.lib.lockfile.UnlockError(path)

Bases: cherrypy.lib.lockfile.LockError

Could not release a lock

msg = 'Unable to unlock %r'
class cherrypy.lib.lockfile.WindowsLockFile(path)

Bases: cherrypy.lib.lockfile.SystemLockFile

cherrypy.lib.locking module

class cherrypy.lib.locking.LockChecker(session_id, timeout)

Bases: object

Keep track of the time and detect if a timeout has expired

expired()
exception cherrypy.lib.locking.LockTimeout

Bases: Exception

An exception when a lock could not be acquired before a timeout period

class cherrypy.lib.locking.NeverExpires

Bases: object

expired()
class cherrypy.lib.locking.Timer(expiration)

Bases: object

A simple timer that will indicate when an expiration time has passed.

classmethod after(elapsed)

Return a timer that will expire after elapsed passes.

expired()

cherrypy.lib.profiler module

Profiler tools for CherryPy.

CherryPy users

You can profile any of your pages as follows:

from cherrypy.lib import profiler

class Root:
    p = profiler.Profiler("/path/to/profile/dir")

    @cherrypy.expose
    def index(self):
        self.p.run(self._index)

    def _index(self):
        return "Hello, world!"

cherrypy.tree.mount(Root())

You can also turn on profiling for all requests using the make_app function as WSGI middleware.

CherryPy developers

This module can be used whenever you make changes to CherryPy, to get a quick sanity-check on overall CP performance. Use the --profile flag when running the test suite. Then, use the serve() function to browse the results in a web browser. If you run this module from the command line, it will call serve() for you.

class cherrypy.lib.profiler.ProfileAggregator(path=None)

Bases: cherrypy.lib.profiler.Profiler

run(func, *args, **params)
class cherrypy.lib.profiler.Profiler(path=None)

Bases: object

index()
menu()
report(filename)
run(func, *args, **params)

Dump profile data into self.path.

statfiles()
Return type:list of available profiles.
stats(filename, sortby='cumulative')
Rtype stats(index):
 output of print_stats() for the given profile.
class cherrypy.lib.profiler.make_app(nextapp, path=None, aggregate=False)

Bases: object

cherrypy.lib.profiler.new_func_strip_path(func_name)

Make profiler output more readable by adding __init__ modules’ parents

cherrypy.lib.profiler.serve(path=None, port=8080)

cherrypy.lib.reprconf module

Generic configuration system using unrepr.

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, Python’s builtin ConfigParser is used (with some extensions).

Namespaces

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

The only key that cannot exist in a namespace is the “environment” entry. This special entry ‘imports’ other config entries from a template stored in the Config.environments dict.

You can define your own namespaces to be called when new config is merged by adding a named handler to Config.namespaces. The name can be any string, and the handler must be either a callable or a context manager.

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

Bases: dict

A dict-like set of configuration data, with defaults and namespaces.

May take a file, filename, or dict.

defaults = {}
environments = {}
namespaces = cherrypy.lib.reprconf.NamespaceSet({'engine': <function _engine_namespace_handler at 0x7fee87c752f0>, 'log': <function <lambda> at 0x7fee877d46a8>, 'checker': <function <lambda> at 0x7fee877d4730>, 'tree': <function _tree_namespace_handler at 0x7fee87c75378>, 'server': <function _server_namespace_handler at 0x7fee87c74f28>})
reset()

Reset self to default values.

update(config)

Update self from a dict, file or filename.

class cherrypy.lib.reprconf.NamespaceSet

Bases: dict

A dict of config namespace names and handlers.

Each config entry should begin with a namespace name; the corresponding namespace handler will be called once for each config entry in that namespace, and will be passed two arguments: the config key (with the namespace removed) and the config value.

Namespace handlers may be any Python callable; they may also be Python 2.5-style ‘context managers’, in which case their __enter__ method should return a callable to be used as the handler. See cherrypy.tools (the Toolbox class) for an example.

copy()
class cherrypy.lib.reprconf.Parser(defaults=None, dict_type=<class 'collections.OrderedDict'>, allow_no_value=False, *, delimiters=('=', ':'), comment_prefixes=('#', ';'), inline_comment_prefixes=None, strict=True, empty_lines_in_values=True, default_section='DEFAULT', interpolation=<object object>)

Bases: configparser.ConfigParser

Sub-class of ConfigParser that keeps the case of options and that raises an exception if the file cannot be read.

as_dict(raw=False, vars=None)

Convert an INI file to a dictionary

dict_from_file(file)
optionxform(optionstr)
read(filenames)
cherrypy.lib.reprconf.as_dict(config)

Return a dict from ‘config’ whether it is a dict, file, or filename.

cherrypy.lib.reprconf.attributes(full_attribute_name)

Load a module and retrieve an attribute of that module.

cherrypy.lib.reprconf.modules(modulePath)

Load a module and retrieve a reference to that module.

cherrypy.lib.reprconf.unrepr(s)

Return a Python object compiled from a string.

cherrypy.lib.sessions module

Session implementation for CherryPy.

You need to edit your config file to use sessions. Here’s an example:

[/]
tools.sessions.on = True
tools.sessions.storage_class = cherrypy.lib.sessions.FileSession
tools.sessions.storage_path = "/home/site/sessions"
tools.sessions.timeout = 60

This sets the session to be stored in files in the directory /home/site/sessions, and the session timeout to 60 minutes. If you omit storage_class, the sessions will be saved in RAM. tools.sessions.on is the only required line for working sessions, the rest are optional.

By default, the session ID is passed in a cookie, so the client’s browser must have cookies enabled for your site.

To set data for the current session, use cherrypy.session['fieldname'] = 'fieldvalue'; to get data use cherrypy.session.get('fieldname').

Locking sessions

By default, the 'locking' mode of sessions is 'implicit', which means the session is locked early and unlocked late. Be mindful of this default mode for any requests that take a long time to process (streaming responses, expensive calculations, database lookups, API calls, etc), as other concurrent requests that also utilize sessions will hang until the session is unlocked.

If you want to control when the session data is locked and unlocked, set tools.sessions.locking = 'explicit'. Then call cherrypy.session.acquire_lock() and cherrypy.session.release_lock(). Regardless of which mode you use, the session is guaranteed to be unlocked when the request is complete.

Expiring Sessions

You can force a session to expire with cherrypy.lib.sessions.expire(). Simply call that function at the point you want the session to expire, and it will cause the session cookie to expire client-side.

Session Fixation Protection

If CherryPy receives, via a request cookie, a session id that it does not recognize, it will reject that id and create a new one to return in the response cookie. This helps prevent session fixation attacks. However, CherryPy “recognizes” a session id by looking up the saved session data for that id. Therefore, if you never save any session data, you will get a new session id for every request.

Sharing Sessions

If you run multiple instances of CherryPy (for example via mod_python behind Apache prefork), you most likely cannot use the RAM session backend, since each instance of CherryPy will have its own memory space. Use a different backend instead, and verify that all instances are pointing at the same file or db location. Alternately, you might try a load balancer which makes sessions “sticky”. Google is your friend, there.

Expiration Dates

The response cookie will possess an expiration date to inform the client at which point to stop sending the cookie back in requests. If the server time and client time differ, expect sessions to be unreliable. Make sure the system time of your server is accurate.

CherryPy defaults to a 60-minute session timeout, which also applies to the cookie which is sent to the client. Unfortunately, some versions of Safari (“4 public beta” on Windows XP at least) appear to have a bug in their parsing of the GMT expiration date–they appear to interpret the date as one hour in the past. Sixty minutes minus one hour is pretty close to zero, so you may experience this bug as a new session id for every request, unless the requests are less than one second apart. To fix, try increasing the session.timeout.

On the other extreme, some users report Firefox sending cookies after their expiration date, although this was on a system with an inaccurate system time. Maybe FF doesn’t trust system time.

class cherrypy.lib.sessions.FileSession(id=None, **kwargs)

Bases: cherrypy.lib.sessions.Session

Implementation of the File backend for sessions

storage_path
The folder where session data will be saved. Each session will be saved as pickle.dump(data, expiration_time) in its own file; the filename will be self.SESSION_PREFIX + self.id.
lock_timeout
A timedelta or numeric seconds indicating how long to block acquiring a lock. If None (default), acquiring a lock will block indefinitely.
LOCK_SUFFIX = '.lock'
SESSION_PREFIX = 'session-'
acquire_lock(path=None)

Acquire an exclusive lock on the currently-loaded session data.

clean_up()

Clean up expired sessions.

pickle_protocol = 4
release_lock(path=None)

Release the lock on the currently-loaded session data.

classmethod setup(**kwargs)

Set up the storage system for file-based sessions.

This should only be called once per process; this will be done automatically when using sessions.init (as the built-in Tool does).

class cherrypy.lib.sessions.MemcachedSession(id=None, **kwargs)

Bases: cherrypy.lib.sessions.Session

acquire_lock()

Acquire an exclusive lock on the currently-loaded session data.

locks = {}
mc_lock = <_thread.RLock owner=0 count=0>
release_lock()

Release the lock on the currently-loaded session data.

servers = ['127.0.0.1:11211']
classmethod setup(**kwargs)

Set up the storage system for memcached-based sessions.

This should only be called once per process; this will be done automatically when using sessions.init (as the built-in Tool does).

class cherrypy.lib.sessions.RamSession(id=None, **kwargs)

Bases: cherrypy.lib.sessions.Session

acquire_lock()

Acquire an exclusive lock on the currently-loaded session data.

cache = {}
clean_up()

Clean up expired sessions.

locks = {}
release_lock()

Release the lock on the currently-loaded session data.

class cherrypy.lib.sessions.Session(id=None, **kwargs)

Bases: object

A CherryPy dict-like Session object (one per request).

clean_freq = 5

The poll rate for expired session cleanup in minutes.

clean_thread = None

Class-level Monitor which calls self.clean_up.

clean_up()

Clean up expired sessions.

clear() → None. Remove all items from D.
debug = False

If True, log debug information.

delete()

Delete stored session data.

generate_id()

Return a new session id.

get(k[, d]) → D[k] if k in D, else d. d defaults to None.
id

The current session ID.

id_observers = None

A list of callbacks to which to pass new id’s.

items() → list of D's (key, value) pairs, as 2-tuples.
keys() → list of D's keys.
load()

Copy stored session data into this session instance.

loaded = False

If True, data has been retrieved from storage. This should happen automatically on the first attempt to access session data.

locked = False

If True, this session instance has exclusive read/write access to session data.

missing = False

True if the session requested by the client did not exist.

now()

Generate the session specific concept of ‘now’.

Other session providers can override this to use alternative, possibly timezone aware, versions of ‘now’.

originalid = None

The session id passed by the client. May be missing or unsafe.

pop(key, default=False)

Remove the specified key and return the corresponding value. If key is not found, default is returned if given, otherwise KeyError is raised.

regenerate()

Replace the current session (with a new id).

regenerated = False

True if the application called session.regenerate(). This is not set by internal calls to regenerate the session id.

save()

Save session data.

setdefault(k[, d]) → D.get(k,d), also set D[k]=d if k not in D.
timeout = 60

Number of minutes after which to delete session data.

update(E) → None. Update D from E: for k in E: D[k] = E[k].
values() → list of D's values.
cherrypy.lib.sessions.close()

Close the session object for this request.

cherrypy.lib.sessions.expire()

Expire the current session cookie.

cherrypy.lib.sessions.init(storage_type=None, path=None, path_header=None, name='session_id', timeout=60, domain=None, secure=False, clean_freq=5, persistent=True, httponly=False, debug=False, **kwargs)

Initialize session object (using cookies).

storage_class
The Session subclass to use. Defaults to RamSession.
storage_type
(deprecated) One of ‘ram’, ‘file’, memcached’. This will be used to look up the corresponding class in cherrypy.lib.sessions globals. For example, ‘file’ will use the FileSession class.
path
The ‘path’ value to stick in the response cookie metadata.
path_header
If ‘path’ is None (the default), then the response cookie ‘path’ will be pulled from request.headers[path_header].
name
The name of the cookie.
timeout
The expiration timeout (in minutes) for the stored session data. If ‘persistent’ is True (the default), this is also the timeout for the cookie.
domain
The cookie domain.
secure
If False (the default) the cookie ‘secure’ value will not be set. If True, the cookie ‘secure’ value will be set (to 1).
clean_freq (minutes)
The poll rate for expired session cleanup.
persistent
If True (the default), the ‘timeout’ argument will be used to expire the cookie. If False, the cookie will not have an expiry, and the cookie will be a “session cookie” which expires when the browser is closed.
httponly
If False (the default) the cookie ‘httponly’ value will not be set. If True, the cookie ‘httponly’ value will be set (to 1).

Any additional kwargs will be bound to the new Session instance, and may be specific to the storage type. See the subclass of Session you’re using for more information.

cherrypy.lib.sessions.save()

Save any changed session data.

Set a response cookie for the client.

path
the ‘path’ value to stick in the response cookie metadata.
path_header
if ‘path’ is None (the default), then the response cookie ‘path’ will be pulled from request.headers[path_header].
name
the name of the cookie.
timeout
the expiration timeout for the cookie. If 0 or other boolean False, no ‘expires’ param will be set, and the cookie will be a “session cookie” which expires when the browser is closed.
domain
the cookie domain.
secure
if False (the default) the cookie ‘secure’ value will not be set. If True, the cookie ‘secure’ value will be set (to 1).
httponly
If False (the default) the cookie ‘httponly’ value will not be set. If True, the cookie ‘httponly’ value will be set (to 1).

cherrypy.lib.static module

cherrypy.lib.static.serve_download(path, name=None)

Serve ‘path’ as an application/x-download attachment.

cherrypy.lib.static.serve_file(path, content_type=None, disposition=None, name=None, debug=False)

Set status, headers, and body in order to serve the given path.

The Content-Type header will be set to the content_type arg, if provided. If not provided, the Content-Type will be guessed by the file extension of the ‘path’ argument.

If disposition is not None, the Content-Disposition header will be set to “<disposition>; filename=<name>”. If name is None, it will be set to the basename of path. If disposition is None, no Content-Disposition header will be written.

cherrypy.lib.static.serve_fileobj(fileobj, content_type=None, disposition=None, name=None, debug=False)

Set status, headers, and body in order to serve the given file object.

The Content-Type header will be set to the content_type arg, if provided.

If disposition is not None, the Content-Disposition header will be set to “<disposition>; filename=<name>”. If name is None, ‘filename’ will not be set. If disposition is None, no Content-Disposition header will be written.

CAUTION: If the request contains a ‘Range’ header, one or more seek()s will be performed on the file object. This may cause undesired behavior if the file object is not seekable. It could also produce undesired results if the caller set the read position of the file object prior to calling serve_fileobj(), expecting that the data would be served starting from that position.

cherrypy.lib.static.staticdir(section, dir, root='', match='', content_types=None, index='', debug=False)

Serve a static resource from the given (root +) dir.

match
If given, request.path_info will be searched for the given regular expression before attempting to serve static content.
content_types
If given, it should be a Python dictionary of {file-extension: content-type} pairs, where ‘file-extension’ is a string (e.g. “gif”) and ‘content-type’ is the value to write out in the Content-Type response header (e.g. “image/gif”).
index
If provided, it should be the (relative) name of a file to serve for directory requests. For example, if the dir argument is ‘/home/me’, the Request-URI is ‘myapp’, and the index arg is ‘index.html’, the file ‘/home/me/myapp/index.html’ will be sought.
cherrypy.lib.static.staticfile(filename, root=None, match='', content_types=None, debug=False)

Serve a static resource from the given (root +) filename.

match
If given, request.path_info will be searched for the given regular expression before attempting to serve static content.
content_types
If given, it should be a Python dictionary of {file-extension: content-type} pairs, where ‘file-extension’ is a string (e.g. “gif”) and ‘content-type’ is the value to write out in the Content-Type response header (e.g. “image/gif”).

cherrypy.lib.xmlrpcutil module

cherrypy.lib.xmlrpcutil.get_xmlrpclib()
cherrypy.lib.xmlrpcutil.on_error(*args, **kwargs)
cherrypy.lib.xmlrpcutil.patched_path(path)

Return ‘path’, doctored for RPC.

cherrypy.lib.xmlrpcutil.process_body()

Return (params, method) from request body.

cherrypy.lib.xmlrpcutil.respond(body, encoding='utf-8', allow_none=0)

Module contents

CherryPy Library

class cherrypy.lib.file_generator(input, chunkSize=65536)

Bases: object

Yield the given input (a file object) in chunks (default 64k). (Core)

next()
cherrypy.lib.file_generator_limited(fileobj, count, chunk_size=65536)

Yield the given file object in chunks, stopping after count bytes has been emitted. Default chunk size is 64kB. (Core)

cherrypy.lib.is_closable_iterator(obj)
cherrypy.lib.is_iterator(obj)

Returns a boolean indicating if the object provided implements the iterator protocol (i.e. like a generator). This will return false for objects which iterable, but not iterators themselves.

cherrypy.lib.set_vary_header(response, header_name)

Add a Vary header to a response