# 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: `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)

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

  property qvalue

    The qvalue, or priority, of this value.

class cherrypy.lib.httputil.CaseInsensitiveDict(*args, **kargs)

  Bases: `KeyTransformingDict`

  A case-insensitive dict subclass.

  Each key is changed on entry to title case.

  static transform_key(key)

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(*args, **kargs)

  Bases: `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_item(item)
  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

class cherrypy.lib.httputil.SanitizedHost(raw)

  Bases: `str`

  Wraps a raw host header received from the network in a sanitized version that elides dangerous characters.

      >>> SanitizedHost('foo\nbar')
      'foobar'
      >>> SanitizedHost('foo\nbar').raw
      'foo\nbar'

  A SanitizedInstance is only returned if sanitization was performed.

      >>> isinstance(SanitizedHost('foobar'), SanitizedHost)
      False

  classmethod _sanitize(raw)
  dangerous = re.compile('[\\n\\r]')

cherrypy.lib.httputil._parse_qs(qs, keep_blank_values=0, strict_parsing=0, encoding='utf-8')

  Parse a query given as a string argument.

  Arguments:

  qs: URL-encoded query string to be parsed

  keep_blank_values: flag indicating whether blank values in

    URL encoded queries should be treated as blank strings. A true value indicates that blanks should be retained as blank strings. The default false value indicates that blank values are to be ignored and treated as if they were not included.

  strict_parsing: flag indicating what to do with parsing errors. If

    false (the default), errors are silently ignored. If true, errors raise a ValueError exception.

  Returns a dict, as G-d intended.

cherrypy.lib.httputil.decode_TEXT(value)

  Decode RFC 2047 TEXT.

      >>> decode_TEXT("=?utf-8?q?f=C3=BCr?=") == b'f\xfcr'.decode('latin-1')
      True

cherrypy.lib.httputil.decode_TEXT_maybe(value)

  Decode the text but only if ‘=?’ appears in it.

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, a str that begins with an int or the constant from `http.client` stdlib module.

  If status has no reason-phrase is supplied, a default reason- phrase will be provided.

      >>> import http.client
      >>> from http.server import BaseHTTPRequestHandler
      >>> valid_status(http.client.ACCEPTED) == (
      ...     int(http.client.ACCEPTED),
      ... ) + BaseHTTPRequestHandler.responses[http.client.ACCEPTED]
      True