Fixed issue-number mistake in NEWS update.
[python.git] / Lib / wsgiref / headers.py
blob6bd304ef97024786c4c9378a3e8a2c60e4653738
1 """Manage HTTP Response Headers
3 Much of this module is red-handedly pilfered from email.message in the stdlib,
4 so portions are Copyright (C) 2001,2002 Python Software Foundation, and were
5 written by Barry Warsaw.
6 """
8 from types import ListType, TupleType
10 # Regular expression that matches `special' characters in parameters, the
11 # existence of which force quoting of the parameter value.
12 import re
13 tspecials = re.compile(r'[ \(\)<>@,;:\\"/\[\]\?=]')
15 def _formatparam(param, value=None, quote=1):
16 """Convenience function to format and return a key=value pair.
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
42 class Headers:
44 """Manage a collection of HTTP response headers"""
46 def __init__(self,headers):
47 if type(headers) is not ListType:
48 raise TypeError("Headers must be a list of name/value tuples")
49 self._headers = headers
51 def __len__(self):
52 """Return the total number of headers, including duplicates."""
53 return len(self._headers)
55 def __setitem__(self, name, val):
56 """Set the value of a header."""
57 del self[name]
58 self._headers.append((name, val))
60 def __delitem__(self,name):
61 """Delete all occurrences of a header, if present.
63 Does *not* raise an exception if the header is missing.
64 """
65 name = name.lower()
66 self._headers[:] = [kv for kv in self._headers if kv[0].lower() != name]
68 def __getitem__(self,name):
69 """Get the first header value for 'name'
71 Return None if the header is missing instead of raising an exception.
73 Note that if the header appeared multiple times, the first exactly which
74 occurrance gets returned is undefined. Use getall() to get all
75 the values matching a header field name.
76 """
77 return self.get(name)
83 def has_key(self, name):
84 """Return true if the message contains the header."""
85 return self.get(name) is not None
87 __contains__ = has_key
90 def get_all(self, name):
91 """Return a list of all the values for the named field.
93 These will be sorted in the order they appeared in the original header
94 list or were added to this instance, and may contain duplicates. Any
95 fields deleted and re-inserted are always appended to the header list.
96 If no fields exist with the given name, returns an empty list.
97 """
98 name = name.lower()
99 return [kv[1] for kv in self._headers if kv[0].lower()==name]
102 def get(self,name,default=None):
103 """Get the first header value for 'name', or return 'default'"""
104 name = name.lower()
105 for k,v in self._headers:
106 if k.lower()==name:
107 return v
108 return default
111 def keys(self):
112 """Return a list of all the header field names.
114 These will be sorted in the order they appeared in the original header
115 list, or were added to this instance, and may contain duplicates.
116 Any fields deleted and re-inserted are always appended to the header
117 list.
119 return [k for k, v in self._headers]
124 def values(self):
125 """Return a list of all header values.
127 These will be sorted in the order they appeared in the original header
128 list, or were added to this instance, and may contain duplicates.
129 Any fields deleted and re-inserted are always appended to the header
130 list.
132 return [v for k, v in self._headers]
134 def items(self):
135 """Get all the header fields and values.
137 These will be sorted in the order they were in the original header
138 list, or were added to this instance, and may contain duplicates.
139 Any fields deleted and re-inserted are always appended to the header
140 list.
142 return self._headers[:]
144 def __repr__(self):
145 return "Headers(%r)" % self._headers
147 def __str__(self):
148 """str() returns the formatted headers, complete with end line,
149 suitable for direct HTTP transmission."""
150 return '\r\n'.join(["%s: %s" % kv for kv in self._headers]+['',''])
152 def setdefault(self,name,value):
153 """Return first matching header value for 'name', or 'value'
155 If there is no header named 'name', add a new header with name 'name'
156 and value 'value'."""
157 result = self.get(name)
158 if result is None:
159 self._headers.append((name,value))
160 return value
161 else:
162 return result
165 def add_header(self, _name, _value, **_params):
166 """Extended header setting.
168 _name is the header field to add. keyword arguments can be used to set
169 additional parameters for the header field, with underscores converted
170 to dashes. Normally the parameter will be added as key="value" unless
171 value is None, in which case only the key will be added.
173 Example:
175 h.add_header('content-disposition', 'attachment', filename='bud.gif')
177 Note that unlike the corresponding 'email.message' method, this does
178 *not* handle '(charset, language, value)' tuples: all values must be
179 strings or None.
181 parts = []
182 if _value is not None:
183 parts.append(_value)
184 for k, v in _params.items():
185 if v is None:
186 parts.append(k.replace('_', '-'))
187 else:
188 parts.append(_formatparam(k.replace('_', '-'), v))
189 self._headers.append((_name, "; ".join(parts)))