# cherrypy.lib.cptools module

Functions for builtin CherryPy tools.

class cherrypy.lib.cptools.MonitoredHeaderMap

  Bases: `HeaderMap`

  transform_key(key)

class cherrypy.lib.cptools.SessionAuth

  Bases: `object`

  Assert that the user is logged in.

  _debug_message(template, context={})
  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.

  This function also processes errors that are subclasses of `exception`.

  Parameters:

    - exception (BaseException) – Exception class to catch.

    - error (int) – The HTTP status 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)

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.