|
1 """Manage HTTP Response Headers |
|
2 |
|
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 """ |
|
7 |
|
8 from types import ListType, TupleType |
|
9 |
|
10 # Regular expression that matches `special' characters in parameters, the |
|
11 # existance of which force quoting of the parameter value. |
|
12 import re |
|
13 tspecials = re.compile(r'[ \(\)<>@,;:\\"/\[\]\?=]') |
|
14 |
|
15 def _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 |
|
30 |
|
31 |
|
32 |
|
33 |
|
34 |
|
35 |
|
36 |
|
37 |
|
38 |
|
39 |
|
40 |
|
41 |
|
42 class Headers: |
|
43 |
|
44 """Manage a collection of HTTP response headers""" |
|
45 |
|
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 |
|
50 |
|
51 def __len__(self): |
|
52 """Return the total number of headers, including duplicates.""" |
|
53 return len(self._headers) |
|
54 |
|
55 def __setitem__(self, name, val): |
|
56 """Set the value of a header.""" |
|
57 del self[name] |
|
58 self._headers.append((name, val)) |
|
59 |
|
60 def __delitem__(self,name): |
|
61 """Delete all occurrences of a header, if present. |
|
62 |
|
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] |
|
67 |
|
68 def __getitem__(self,name): |
|
69 """Get the first header value for 'name' |
|
70 |
|
71 Return None if the header is missing instead of raising an exception. |
|
72 |
|
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) |
|
78 |
|
79 |
|
80 |
|
81 |
|
82 |
|
83 def has_key(self, name): |
|
84 """Return true if the message contains the header.""" |
|
85 return self.get(name) is not None |
|
86 |
|
87 __contains__ = has_key |
|
88 |
|
89 |
|
90 def get_all(self, name): |
|
91 """Return a list of all the values for the named field. |
|
92 |
|
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] |
|
100 |
|
101 |
|
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 |
|
109 |
|
110 |
|
111 def keys(self): |
|
112 """Return a list of all the header field names. |
|
113 |
|
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. |
|
118 """ |
|
119 return [k for k, v in self._headers] |
|
120 |
|
121 |
|
122 |
|
123 |
|
124 def values(self): |
|
125 """Return a list of all header values. |
|
126 |
|
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. |
|
131 """ |
|
132 return [v for k, v in self._headers] |
|
133 |
|
134 def items(self): |
|
135 """Get all the header fields and values. |
|
136 |
|
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. |
|
141 """ |
|
142 return self._headers[:] |
|
143 |
|
144 def __repr__(self): |
|
145 return "Headers(%r)" % self._headers |
|
146 |
|
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]+['','']) |
|
151 |
|
152 def setdefault(self,name,value): |
|
153 """Return first matching header value for 'name', or 'value' |
|
154 |
|
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 |
|
163 |
|
164 |
|
165 def add_header(self, _name, _value, **_params): |
|
166 """Extended header setting. |
|
167 |
|
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. |
|
172 |
|
173 Example: |
|
174 |
|
175 h.add_header('content-disposition', 'attachment', filename='bud.gif') |
|
176 |
|
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. |
|
180 """ |
|
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))) |
|
190 |
|
191 |
|
192 |
|
193 |
|
194 |
|
195 |
|
196 |
|
197 |
|
198 |
|
199 |
|
200 |
|
201 |
|
202 |
|
203 |
|
204 |
|
205 # |