jpayne@68: """Manage HTTP Response Headers jpayne@68: jpayne@68: Much of this module is red-handedly pilfered from email.message in the stdlib, jpayne@68: so portions are Copyright (C) 2001,2002 Python Software Foundation, and were jpayne@68: written by Barry Warsaw. jpayne@68: """ jpayne@68: jpayne@68: # Regular expression that matches `special' characters in parameters, the jpayne@68: # existence of which force quoting of the parameter value. jpayne@68: import re jpayne@68: tspecials = re.compile(r'[ \(\)<>@,;:\\"/\[\]\?=]') jpayne@68: jpayne@68: def _formatparam(param, value=None, quote=1): jpayne@68: """Convenience function to format and return a key=value pair. jpayne@68: jpayne@68: This will quote the value if needed or if quote is true. jpayne@68: """ jpayne@68: if value is not None and len(value) > 0: jpayne@68: if quote or tspecials.search(value): jpayne@68: value = value.replace('\\', '\\\\').replace('"', r'\"') jpayne@68: return '%s="%s"' % (param, value) jpayne@68: else: jpayne@68: return '%s=%s' % (param, value) jpayne@68: else: jpayne@68: return param jpayne@68: jpayne@68: jpayne@68: class Headers: jpayne@68: """Manage a collection of HTTP response headers""" jpayne@68: jpayne@68: def __init__(self, headers=None): jpayne@68: headers = headers if headers is not None else [] jpayne@68: if type(headers) is not list: jpayne@68: raise TypeError("Headers must be a list of name/value tuples") jpayne@68: self._headers = headers jpayne@68: if __debug__: jpayne@68: for k, v in headers: jpayne@68: self._convert_string_type(k) jpayne@68: self._convert_string_type(v) jpayne@68: jpayne@68: def _convert_string_type(self, value): jpayne@68: """Convert/check value type.""" jpayne@68: if type(value) is str: jpayne@68: return value jpayne@68: raise AssertionError("Header names/values must be" jpayne@68: " of type str (got {0})".format(repr(value))) jpayne@68: jpayne@68: def __len__(self): jpayne@68: """Return the total number of headers, including duplicates.""" jpayne@68: return len(self._headers) jpayne@68: jpayne@68: def __setitem__(self, name, val): jpayne@68: """Set the value of a header.""" jpayne@68: del self[name] jpayne@68: self._headers.append( jpayne@68: (self._convert_string_type(name), self._convert_string_type(val))) jpayne@68: jpayne@68: def __delitem__(self,name): jpayne@68: """Delete all occurrences of a header, if present. jpayne@68: jpayne@68: Does *not* raise an exception if the header is missing. jpayne@68: """ jpayne@68: name = self._convert_string_type(name.lower()) jpayne@68: self._headers[:] = [kv for kv in self._headers if kv[0].lower() != name] jpayne@68: jpayne@68: def __getitem__(self,name): jpayne@68: """Get the first header value for 'name' jpayne@68: jpayne@68: Return None if the header is missing instead of raising an exception. jpayne@68: jpayne@68: Note that if the header appeared multiple times, the first exactly which jpayne@68: occurrence gets returned is undefined. Use getall() to get all jpayne@68: the values matching a header field name. jpayne@68: """ jpayne@68: return self.get(name) jpayne@68: jpayne@68: def __contains__(self, name): jpayne@68: """Return true if the message contains the header.""" jpayne@68: return self.get(name) is not None jpayne@68: jpayne@68: jpayne@68: def get_all(self, name): jpayne@68: """Return a list of all the values for the named field. jpayne@68: jpayne@68: These will be sorted in the order they appeared in the original header jpayne@68: list or were added to this instance, and may contain duplicates. Any jpayne@68: fields deleted and re-inserted are always appended to the header list. jpayne@68: If no fields exist with the given name, returns an empty list. jpayne@68: """ jpayne@68: name = self._convert_string_type(name.lower()) jpayne@68: return [kv[1] for kv in self._headers if kv[0].lower()==name] jpayne@68: jpayne@68: jpayne@68: def get(self,name,default=None): jpayne@68: """Get the first header value for 'name', or return 'default'""" jpayne@68: name = self._convert_string_type(name.lower()) jpayne@68: for k,v in self._headers: jpayne@68: if k.lower()==name: jpayne@68: return v jpayne@68: return default jpayne@68: jpayne@68: jpayne@68: def keys(self): jpayne@68: """Return a list of all the header field names. jpayne@68: jpayne@68: These will be sorted in the order they appeared in the original header jpayne@68: list, or were added to this instance, and may contain duplicates. jpayne@68: Any fields deleted and re-inserted are always appended to the header jpayne@68: list. jpayne@68: """ jpayne@68: return [k for k, v in self._headers] jpayne@68: jpayne@68: def values(self): jpayne@68: """Return a list of all header values. jpayne@68: jpayne@68: These will be sorted in the order they appeared in the original header jpayne@68: list, or were added to this instance, and may contain duplicates. jpayne@68: Any fields deleted and re-inserted are always appended to the header jpayne@68: list. jpayne@68: """ jpayne@68: return [v for k, v in self._headers] jpayne@68: jpayne@68: def items(self): jpayne@68: """Get all the header fields and values. jpayne@68: jpayne@68: These will be sorted in the order they were in the original header jpayne@68: list, or were added to this instance, and may contain duplicates. jpayne@68: Any fields deleted and re-inserted are always appended to the header jpayne@68: list. jpayne@68: """ jpayne@68: return self._headers[:] jpayne@68: jpayne@68: def __repr__(self): jpayne@68: return "%s(%r)" % (self.__class__.__name__, self._headers) jpayne@68: jpayne@68: def __str__(self): jpayne@68: """str() returns the formatted headers, complete with end line, jpayne@68: suitable for direct HTTP transmission.""" jpayne@68: return '\r\n'.join(["%s: %s" % kv for kv in self._headers]+['','']) jpayne@68: jpayne@68: def __bytes__(self): jpayne@68: return str(self).encode('iso-8859-1') jpayne@68: jpayne@68: def setdefault(self,name,value): jpayne@68: """Return first matching header value for 'name', or 'value' jpayne@68: jpayne@68: If there is no header named 'name', add a new header with name 'name' jpayne@68: and value 'value'.""" jpayne@68: result = self.get(name) jpayne@68: if result is None: jpayne@68: self._headers.append((self._convert_string_type(name), jpayne@68: self._convert_string_type(value))) jpayne@68: return value jpayne@68: else: jpayne@68: return result jpayne@68: jpayne@68: def add_header(self, _name, _value, **_params): jpayne@68: """Extended header setting. jpayne@68: jpayne@68: _name is the header field to add. keyword arguments can be used to set jpayne@68: additional parameters for the header field, with underscores converted jpayne@68: to dashes. Normally the parameter will be added as key="value" unless jpayne@68: value is None, in which case only the key will be added. jpayne@68: jpayne@68: Example: jpayne@68: jpayne@68: h.add_header('content-disposition', 'attachment', filename='bud.gif') jpayne@68: jpayne@68: Note that unlike the corresponding 'email.message' method, this does jpayne@68: *not* handle '(charset, language, value)' tuples: all values must be jpayne@68: strings or None. jpayne@68: """ jpayne@68: parts = [] jpayne@68: if _value is not None: jpayne@68: _value = self._convert_string_type(_value) jpayne@68: parts.append(_value) jpayne@68: for k, v in _params.items(): jpayne@68: k = self._convert_string_type(k) jpayne@68: if v is None: jpayne@68: parts.append(k.replace('_', '-')) jpayne@68: else: jpayne@68: v = self._convert_string_type(v) jpayne@68: parts.append(_formatparam(k.replace('_', '-'), v)) jpayne@68: self._headers.append((self._convert_string_type(_name), "; ".join(parts)))