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