This :class:`MultiDict` subclass is used to store request form data. Additionally to the normal dict-like item access methods (which return unmodified data as native strings), this container also supports attribute-like access to its values. Attributes are automatically de-
| 2181 | |
| 2182 | |
| 2183 | class FormsDict(MultiDict): |
| 2184 | """ This :class:`MultiDict` subclass is used to store request form data. |
| 2185 | Additionally to the normal dict-like item access methods (which return |
| 2186 | unmodified data as native strings), this container also supports |
| 2187 | attribute-like access to its values. Attributes are automatically de- |
| 2188 | or recoded to match :attr:`input_encoding` (default: 'utf8'). Missing |
| 2189 | attributes default to an empty string. """ |
| 2190 | |
| 2191 | #: Encoding used for attribute values. |
| 2192 | input_encoding = 'utf8' |
| 2193 | #: If true (default), unicode strings are first encoded with `latin1` |
| 2194 | #: and then decoded to match :attr:`input_encoding`. |
| 2195 | recode_unicode = True |
| 2196 | |
| 2197 | def _fix(self, s, encoding=None): |
| 2198 | if isinstance(s, unicode) and self.recode_unicode: # Python 3 WSGI |
| 2199 | return s.encode('latin1').decode(encoding or self.input_encoding) |
| 2200 | elif isinstance(s, bytes): # Python 2 WSGI |
| 2201 | return s.decode(encoding or self.input_encoding) |
| 2202 | else: |
| 2203 | return s |
| 2204 | |
| 2205 | def decode(self, encoding=None): |
| 2206 | """ Returns a copy with all keys and values de- or recoded to match |
| 2207 | :attr:`input_encoding`. Some libraries (e.g. WTForms) want a |
| 2208 | unicode dictionary. """ |
| 2209 | copy = FormsDict() |
| 2210 | enc = copy.input_encoding = encoding or self.input_encoding |
| 2211 | copy.recode_unicode = False |
| 2212 | for key, value in self.allitems(): |
| 2213 | copy.append(self._fix(key, enc), self._fix(value, enc)) |
| 2214 | return copy |
| 2215 | |
| 2216 | def getunicode(self, name, default=None, encoding=None): |
| 2217 | """ Return the value as a unicode string, or the default. """ |
| 2218 | try: |
| 2219 | return self._fix(self[name], encoding) |
| 2220 | except (UnicodeError, KeyError): |
| 2221 | return default |
| 2222 | |
| 2223 | def __getattr__(self, name, default=unicode()): |
| 2224 | # Without this guard, pickle generates a cryptic TypeError: |
| 2225 | if name.startswith('__') and name.endswith('__'): |
| 2226 | return super(FormsDict, self).__getattr__(name) |
| 2227 | return self.getunicode(name, default=default) |
| 2228 | |
| 2229 | class HeaderDict(MultiDict): |
| 2230 | """ A case-insensitive version of :class:`MultiDict` that defaults to |