Thomas Wouters | 0e3f591 | 2006-08-11 14:57:12 +0000 | [diff] [blame] | 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() |
Guido van Rossum | b053cd8 | 2006-08-24 03:53:23 +0000 | [diff] [blame] | 66 | self._headers[:] = [kv for kv in self._headers if kv[0].lower() != name] |
Thomas Wouters | 0e3f591 | 2006-08-11 14:57:12 +0000 | [diff] [blame] | 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 | |
Guido van Rossum | e2b70bc | 2006-08-18 22:13:04 +0000 | [diff] [blame] | 83 | def __contains__(self, name): |
Thomas Wouters | 0e3f591 | 2006-08-11 14:57:12 +0000 | [diff] [blame] | 84 | """Return true if the message contains the header.""" |
| 85 | return self.get(name) is not None |
| 86 | |
Thomas Wouters | 0e3f591 | 2006-08-11 14:57:12 +0000 | [diff] [blame] | 87 | |
| 88 | def get_all(self, name): |
| 89 | """Return a list of all the values for the named field. |
| 90 | |
| 91 | These will be sorted in the order they appeared in the original header |
| 92 | list or were added to this instance, and may contain duplicates. Any |
| 93 | fields deleted and re-inserted are always appended to the header list. |
| 94 | If no fields exist with the given name, returns an empty list. |
| 95 | """ |
| 96 | name = name.lower() |
| 97 | return [kv[1] for kv in self._headers if kv[0].lower()==name] |
| 98 | |
| 99 | |
| 100 | def get(self,name,default=None): |
| 101 | """Get the first header value for 'name', or return 'default'""" |
| 102 | name = name.lower() |
| 103 | for k,v in self._headers: |
| 104 | if k.lower()==name: |
| 105 | return v |
| 106 | return default |
| 107 | |
| 108 | |
| 109 | def keys(self): |
| 110 | """Return a list of all the header field names. |
| 111 | |
| 112 | These will be sorted in the order they appeared in the original header |
| 113 | list, or were added to this instance, and may contain duplicates. |
| 114 | Any fields deleted and re-inserted are always appended to the header |
| 115 | list. |
| 116 | """ |
| 117 | return [k for k, v in self._headers] |
| 118 | |
| 119 | |
| 120 | |
| 121 | |
| 122 | def values(self): |
| 123 | """Return a list of all header values. |
| 124 | |
| 125 | These will be sorted in the order they appeared in the original header |
| 126 | list, or were added to this instance, and may contain duplicates. |
| 127 | Any fields deleted and re-inserted are always appended to the header |
| 128 | list. |
| 129 | """ |
| 130 | return [v for k, v in self._headers] |
| 131 | |
| 132 | def items(self): |
| 133 | """Get all the header fields and values. |
| 134 | |
| 135 | These will be sorted in the order they were in the original header |
| 136 | list, or were added to this instance, and may contain duplicates. |
| 137 | Any fields deleted and re-inserted are always appended to the header |
| 138 | list. |
| 139 | """ |
| 140 | return self._headers[:] |
| 141 | |
| 142 | def __repr__(self): |
Brett Cannon | 0b70cca | 2006-08-25 02:59:59 +0000 | [diff] [blame] | 143 | return "Headers(%r)" % self._headers |
Thomas Wouters | 0e3f591 | 2006-08-11 14:57:12 +0000 | [diff] [blame] | 144 | |
| 145 | def __str__(self): |
| 146 | """str() returns the formatted headers, complete with end line, |
| 147 | suitable for direct HTTP transmission.""" |
| 148 | return '\r\n'.join(["%s: %s" % kv for kv in self._headers]+['','']) |
| 149 | |
| 150 | def setdefault(self,name,value): |
| 151 | """Return first matching header value for 'name', or 'value' |
| 152 | |
| 153 | If there is no header named 'name', add a new header with name 'name' |
| 154 | and value 'value'.""" |
| 155 | result = self.get(name) |
| 156 | if result is None: |
| 157 | self._headers.append((name,value)) |
| 158 | return value |
| 159 | else: |
| 160 | return result |
| 161 | |
| 162 | |
| 163 | def add_header(self, _name, _value, **_params): |
| 164 | """Extended header setting. |
| 165 | |
| 166 | _name is the header field to add. keyword arguments can be used to set |
| 167 | additional parameters for the header field, with underscores converted |
| 168 | to dashes. Normally the parameter will be added as key="value" unless |
| 169 | value is None, in which case only the key will be added. |
| 170 | |
| 171 | Example: |
| 172 | |
| 173 | h.add_header('content-disposition', 'attachment', filename='bud.gif') |
| 174 | |
| 175 | Note that unlike the corresponding 'email.Message' method, this does |
| 176 | *not* handle '(charset, language, value)' tuples: all values must be |
| 177 | strings or None. |
| 178 | """ |
| 179 | parts = [] |
| 180 | if _value is not None: |
| 181 | parts.append(_value) |
| 182 | for k, v in _params.items(): |
| 183 | if v is None: |
| 184 | parts.append(k.replace('_', '-')) |
| 185 | else: |
| 186 | parts.append(_formatparam(k.replace('_', '-'), v)) |
| 187 | self._headers.append((_name, "; ".join(parts))) |
| 188 | |
| 189 | |
| 190 | |
| 191 | |
| 192 | |
| 193 | |
| 194 | |
| 195 | |
| 196 | |
| 197 | |
| 198 | |
| 199 | |
| 200 | |
| 201 | |
| 202 | |
| 203 | # |