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.


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

Bases: dict

A storage system for cached items which reduces stampede collisions.

wait(key, timeout=5, debug=False)[source]

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

Bases: object

Base class for Cache implementations.


Reset the cache to its initial, empty state.


Remove ALL cached variants of the current resource.


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

put(obj, size)[source]

Store the current variant in the cache.

class cherrypy.lib.caching.MemoryCache[source]

Bases: Cache

An in-memory cache for varying response content.

Each key in 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[uri].selecting_headers.

The items contained in[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.


Reset the cache to its initial, empty state.

debug = False
delay = 600

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


Remove ALL cached variants of the current resource.


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.


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

Store the current variant in the cache.

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

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


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


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

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

  • 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

  • sets request.cached = False

  • sets request.cacheable = True

  • returns False


Tee response output to cache storage.