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.
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.
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.
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
)
25 return '%s=%s' % (param
, value
)
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
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."""
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.
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.
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.
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'"""
105 for k
,v
in self
._headers
:
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
119 return [k
for k
, v
in self
._headers
]
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
132 return [v
for k
, v
in self
._headers
]
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
142 return self
._headers
[:]
145 return "Headers(%r)" % self
._headers
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
)
159 self
._headers
.append((name
,value
))
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.
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
182 if _value
is not None:
184 for k
, v
in _params
.items():
186 parts
.append(k
.replace('_', '-'))
188 parts
.append(_formatparam(k
.replace('_', '-'), v
))
189 self
._headers
.append((_name
, "; ".join(parts
)))