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 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 # Disallowed characters for headers and values.
13 # HTAB (\x09) is allowed in header values, but
14 # not in header names. (RFC 9110 Section 5.5)
15 _name_disallowed_re = re.compile(r'[\x00-\x1F\x7F]')
16 _value_disallowed_re = re.compile(r'[\x00-\x08\x0A-\x1F\x7F]')
17
18 def _formatparam(param, value=None, quote=1):
19 """Convenience function to format and return a key=value pair.
20
21 This will quote the value if needed or if quote is true.
22 """
23 if value is not None and len(value) > 0:
24 if quote or tspecials.search(value):
25 value = value.replace('\\', '\\\\').replace('"', r'\"')
26 return '%s="%s"' % (param, value)
27 else:
28 return '%s=%s' % (param, value)
29 else:
30 return param
31
32
33 class Headers:
34 """Manage a collection of HTTP response headers"""
35
36 def __init__(self, headers=None):
37 headers = headers if headers is not None else []
38 if type(headers) is not list:
39 raise TypeError("Headers must be a list of name/value tuples")
40 self._headers = headers
41 if __debug__:
42 for k, v in headers:
43 self._convert_string_type(k, name=True)
44 self._convert_string_type(v, name=False)
45
46 def _convert_string_type(self, value, *, name):
47 """Convert/check value type."""
48 if type(value) is str:
49 regex = (_name_disallowed_re if name else _value_disallowed_re)
50 if regex.search(value):
51 raise ValueError("Control characters not allowed in headers")
52 return value
53 raise AssertionError("Header names/values must be"
54 " of type str (got {0})".format(repr(value)))
55
56 def __len__(self):
57 """Return the total number of headers, including duplicates."""
58 return len(self._headers)
59
60 def __setitem__(self, name, val):
61 """Set the value of a header."""
62 del self[name]
63 self._headers.append(
64 (self._convert_string_type(name, name=True), self._convert_string_type(val, name=False)))
65
66 def __delitem__(self,name):
67 """Delete all occurrences of a header, if present.
68
69 Does *not* raise an exception if the header is missing.
70 """
71 name = self._convert_string_type(name.lower(), name=True)
72 self._headers[:] = [kv for kv in self._headers if kv[0].lower() != name]
73
74 def __getitem__(self,name):
75 """Get the first header value for 'name'
76
77 Return None if the header is missing instead of raising an exception.
78
79 Note that if the header appeared multiple times, the first exactly which
80 occurrence gets returned is undefined. Use getall() to get all
81 the values matching a header field name.
82 """
83 return self.get(name)
84
85 def __contains__(self, name):
86 """Return true if the message contains the header."""
87 return self.get(name) is not None
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 = self._convert_string_type(name.lower(), name=True)
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 = self._convert_string_type(name.lower(), name=True)
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 def values(self):
122 """Return a list of all header values.
123
124 These will be sorted in the order they appeared in the original header
125 list, or were added to this instance, and may contain duplicates.
126 Any fields deleted and re-inserted are always appended to the header
127 list.
128 """
129 return [v for k, v in self._headers]
130
131 def items(self):
132 """Get all the header fields and values.
133
134 These will be sorted in the order they were in the original header
135 list, or were added to this instance, and may contain duplicates.
136 Any fields deleted and re-inserted are always appended to the header
137 list.
138 """
139 return self._headers[:]
140
141 def __repr__(self):
142 return "%s(%r)" % (self.__class__.__name__, self._headers)
143
144 def __str__(self):
145 """str() returns the formatted headers, complete with end line,
146 suitable for direct HTTP transmission."""
147 return '\r\n'.join(["%s: %s" % kv for kv in self._headers]+['',''])
148
149 def __bytes__(self):
150 return str(self).encode('iso-8859-1')
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((self._convert_string_type(name, name=True),
160 self._convert_string_type(value, name=False)))
161 return value
162 else:
163 return result
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 _value = self._convert_string_type(_value, name=False)
184 parts.append(_value)
185 for k, v in _params.items():
186 k = self._convert_string_type(k, name=True)
187 if v is None:
188 parts.append(k.replace('_', '-'))
189 else:
190 v = self._convert_string_type(v, name=False)
191 parts.append(_formatparam(k.replace('_', '-'), v))
192 self._headers.append((self._convert_string_type(_name, name=True), "; ".join(parts)))