• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1"""Manage HTTP Response Headers
2
3Much of this module is red-handedly pilfered from email.message in the stdlib,
4so portions are Copyright (C) 2001,2002 Python Software Foundation, and were
5written by Barry Warsaw.
6"""
7
8from types import ListType, TupleType
9
10# Regular expression that matches `special' characters in parameters, the
11# existence of which force quoting of the parameter value.
12import re
13tspecials = re.compile(r'[ \(\)<>@,;:\\"/\[\]\?=]')
14
15def _formatparam(param, value=None, quote=1):
16    """Convenience function to format and return a key=value pair.
17
18    This will quote the value if needed or if quote is true.
19    """
20    if value is not None and len(value) > 0:
21        if quote or tspecials.search(value):
22            value = value.replace('\\', '\\\\').replace('"', r'\"')
23            return '%s="%s"' % (param, value)
24        else:
25            return '%s=%s' % (param, value)
26    else:
27        return param
28
29
30class Headers:
31
32    """Manage a collection of HTTP response headers"""
33
34    def __init__(self,headers):
35        if type(headers) is not ListType:
36            raise TypeError("Headers must be a list of name/value tuples")
37        self._headers = headers
38
39    def __len__(self):
40        """Return the total number of headers, including duplicates."""
41        return len(self._headers)
42
43    def __setitem__(self, name, val):
44        """Set the value of a header."""
45        del self[name]
46        self._headers.append((name, val))
47
48    def __delitem__(self,name):
49        """Delete all occurrences of a header, if present.
50
51        Does *not* raise an exception if the header is missing.
52        """
53        name = name.lower()
54        self._headers[:] = [kv for kv in self._headers if kv[0].lower() != name]
55
56    def __getitem__(self,name):
57        """Get the first header value for 'name'
58
59        Return None if the header is missing instead of raising an exception.
60
61        Note that if the header appeared multiple times, the first exactly which
62        occurrance gets returned is undefined.  Use getall() to get all
63        the values matching a header field name.
64        """
65        return self.get(name)
66
67    def has_key(self, name):
68        """Return true if the message contains the header."""
69        return self.get(name) is not None
70
71    __contains__ = has_key
72
73
74    def get_all(self, name):
75        """Return a list of all the values for the named field.
76
77        These will be sorted in the order they appeared in the original header
78        list or were added to this instance, and may contain duplicates.  Any
79        fields deleted and re-inserted are always appended to the header list.
80        If no fields exist with the given name, returns an empty list.
81        """
82        name = name.lower()
83        return [kv[1] for kv in self._headers if kv[0].lower()==name]
84
85
86    def get(self,name,default=None):
87        """Get the first header value for 'name', or return 'default'"""
88        name = name.lower()
89        for k,v in self._headers:
90            if k.lower()==name:
91                return v
92        return default
93
94
95    def keys(self):
96        """Return a list of all the header field names.
97
98        These will be sorted in the order they appeared in the original header
99        list, or were added to this instance, and may contain duplicates.
100        Any fields deleted and re-inserted are always appended to the header
101        list.
102        """
103        return [k for k, v in self._headers]
104
105    def values(self):
106        """Return a list of all header values.
107
108        These will be sorted in the order they appeared in the original header
109        list, or were added to this instance, and may contain duplicates.
110        Any fields deleted and re-inserted are always appended to the header
111        list.
112        """
113        return [v for k, v in self._headers]
114
115    def items(self):
116        """Get all the header fields and values.
117
118        These will be sorted in the order they were in the original header
119        list, or were added to this instance, and may contain duplicates.
120        Any fields deleted and re-inserted are always appended to the header
121        list.
122        """
123        return self._headers[:]
124
125    def __repr__(self):
126        return "Headers(%r)" % self._headers
127
128    def __str__(self):
129        """str() returns the formatted headers, complete with end line,
130        suitable for direct HTTP transmission."""
131        return '\r\n'.join(["%s: %s" % kv for kv in self._headers]+['',''])
132
133    def setdefault(self,name,value):
134        """Return first matching header value for 'name', or 'value'
135
136        If there is no header named 'name', add a new header with name 'name'
137        and value 'value'."""
138        result = self.get(name)
139        if result is None:
140            self._headers.append((name,value))
141            return value
142        else:
143            return result
144
145    def add_header(self, _name, _value, **_params):
146        """Extended header setting.
147
148        _name is the header field to add.  keyword arguments can be used to set
149        additional parameters for the header field, with underscores converted
150        to dashes.  Normally the parameter will be added as key="value" unless
151        value is None, in which case only the key will be added.
152
153        Example:
154
155        h.add_header('content-disposition', 'attachment', filename='bud.gif')
156
157        Note that unlike the corresponding 'email.message' method, this does
158        *not* handle '(charset, language, value)' tuples: all values must be
159        strings or None.
160        """
161        parts = []
162        if _value is not None:
163            parts.append(_value)
164        for k, v in _params.items():
165            if v is None:
166                parts.append(k.replace('_', '-'))
167            else:
168                parts.append(_formatparam(k.replace('_', '-'), v))
169        self._headers.append((_name, "; ".join(parts)))
170