Debian Codegraph @

Lib/wsgiref/headers.py

raw
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 # Regular expression that matches `special' characters in parameters, the
9 # existence of which force quoting of the parameter value.
10 import re
11 tspecials = re.compile(r'[ \(\)<>@,;:\\"/\[\]\?=]')
12 _control_chars_re = re.compile(r'[\x00-\x1F\x7F]')
13
14 def _formatparam(param, value=None, quote=1):
15 """Convenience function to format and return a key=value pair.
16
17 This will quote the value if needed or if quote is true.
18 """
19 if value is not None and len(value) > 0:
20 if quote or tspecials.search(value):
21 value = value.replace('\\', '\\\\').replace('"', r'\"')
22 return '%s="%s"' % (param, value)
23 else:
24 return '%s=%s' % (param, value)
25 else:
26 return param
27
28
29 class Headers:
30 """Manage a collection of HTTP response headers"""
31
32 def __init__(self, headers=None):
33 headers = headers if headers is not None else []
34 if type(headers) is not list:
35 raise TypeError("Headers must be a list of name/value tuples")
36 self._headers = headers
37 if __debug__:
38 for k, v in headers:
39 self._convert_string_type(k)
40 self._convert_string_type(v)
41
42 def _convert_string_type(self, value):
43 """Convert/check value type."""
44 if type(value) is str:
45 if _control_chars_re.search(value):
46 raise ValueError("Control characters not allowed in headers")
47 return value
48 raise AssertionError("Header names/values must be"
49 " of type str (got {0})".format(repr(value)))
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(
59 (self._convert_string_type(name), self._convert_string_type(val)))
60
61 def __delitem__(self,name):
62 """Delete all occurrences of a header, if present.
63
64 Does *not* raise an exception if the header is missing.
65 """
66 name = self._convert_string_type(name.lower())
67 self._headers[:] = [kv for kv in self._headers if kv[0].lower() != name]
68
69 def __getitem__(self,name):
70 """Get the first header value for 'name'
71
72 Return None if the header is missing instead of raising an exception.
73
74 Note that if the header appeared multiple times, the first exactly which
75 occurrence gets returned is undefined. Use getall() to get all
76 the values matching a header field name.
77 """
78 return self.get(name)
79
80 def __contains__(self, name):
81 """Return true if the message contains the header."""
82 return self.get(name) is not None
83
84
85 def get_all(self, name):
86 """Return a list of all the values for the named field.
87
88 These will be sorted in the order they appeared in the original header
89 list or were added to this instance, and may contain duplicates. Any
90 fields deleted and re-inserted are always appended to the header list.
91 If no fields exist with the given name, returns an empty list.
92 """
93 name = self._convert_string_type(name.lower())
94 return [kv[1] for kv in self._headers if kv[0].lower()==name]
95
96
97 def get(self,name,default=None):
98 """Get the first header value for 'name', or return 'default'"""
99 name = self._convert_string_type(name.lower())
100 for k,v in self._headers:
101 if k.lower()==name:
102 return v
103 return default
104
105
106 def keys(self):
107 """Return a list of all the header field names.
108
109 These will be sorted in the order they appeared in the original header
110 list, or were added to this instance, and may contain duplicates.
111 Any fields deleted and re-inserted are always appended to the header
112 list.
113 """
114 return [k for k, v in self._headers]
115
116 def values(self):
117 """Return a list of all header values.
118
119 These will be sorted in the order they appeared in the original header
120 list, or were added to this instance, and may contain duplicates.
121 Any fields deleted and re-inserted are always appended to the header
122 list.
123 """
124 return [v for k, v in self._headers]
125
126 def items(self):
127 """Get all the header fields and values.
128
129 These will be sorted in the order they were in the original header
130 list, or were added to this instance, and may contain duplicates.
131 Any fields deleted and re-inserted are always appended to the header
132 list.
133 """
134 return self._headers[:]
135
136 def __repr__(self):
137 return "%s(%r)" % (self.__class__.__name__, self._headers)
138
139 def __str__(self):
140 """str() returns the formatted headers, complete with end line,
141 suitable for direct HTTP transmission."""
142 return '\r\n'.join(["%s: %s" % kv for kv in self._headers]+['',''])
143
144 def __bytes__(self):
145 return str(self).encode('iso-8859-1')
146
147 def setdefault(self,name,value):
148 """Return first matching header value for 'name', or 'value'
149
150 If there is no header named 'name', add a new header with name 'name'
151 and value 'value'."""
152 result = self.get(name)
153 if result is None:
154 self._headers.append((self._convert_string_type(name),
155 self._convert_string_type(value)))
156 return value
157 else:
158 return result
159
160 def add_header(self, _name, _value, **_params):
161 """Extended header setting.
162
163 _name is the header field to add. keyword arguments can be used to set
164 additional parameters for the header field, with underscores converted
165 to dashes. Normally the parameter will be added as key="value" unless
166 value is None, in which case only the key will be added.
167
168 Example:
169
170 h.add_header('content-disposition', 'attachment', filename='bud.gif')
171
172 Note that unlike the corresponding 'email.message' method, this does
173 *not* handle '(charset, language, value)' tuples: all values must be
174 strings or None.
175 """
176 parts = []
177 if _value is not None:
178 _value = self._convert_string_type(_value)
179 parts.append(_value)
180 for k, v in _params.items():
181 k = self._convert_string_type(k)
182 if v is None:
183 parts.append(k.replace('_', '-'))
184 else:
185 v = self._convert_string_type(v)
186 parts.append(_formatparam(k.replace('_', '-'), v))
187 self._headers.append((self._convert_string_type(_name), "; ".join(parts)))