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-
| 2579 | |
| 2580 | |
| 2581 | class FormsDict(MultiDict): |
| 2582 | """ This :class:`MultiDict` subclass is used to store request form data. |
| 2583 | Additionally to the normal dict-like item access methods (which return |
| 2584 | unmodified data as native strings), this container also supports |
| 2585 | attribute-like access to its values. Attributes are automatically de- |
| 2586 | or recoded to match :attr:`input_encoding` (default: 'utf8'). Missing |
| 2587 | attributes default to an empty string. """ |
| 2588 | |
| 2589 | #: Encoding used for attribute values. |
| 2590 | input_encoding = 'utf8' |
| 2591 | #: If true (default), unicode strings are first encoded with `latin1` |
| 2592 | #: and then decoded to match :attr:`input_encoding`. |
| 2593 | recode_unicode = True |
| 2594 | |
| 2595 | def _fix(self, s, encoding=None): |
| 2596 | if isinstance(s, unicode) and self.recode_unicode: # Python 3 WSGI |
| 2597 | return s.encode('latin1').decode(encoding or self.input_encoding) |
| 2598 | elif isinstance(s, bytes): # Python 2 WSGI |
| 2599 | return s.decode(encoding or self.input_encoding) |
| 2600 | else: |
| 2601 | return s |
| 2602 | |
| 2603 | def decode(self, encoding=None): |
| 2604 | """ Returns a copy with all keys and values de- or recoded to match |
| 2605 | :attr:`input_encoding`. Some libraries (e.g. WTForms) want a |
| 2606 | unicode dictionary. """ |
| 2607 | copy = FormsDict() |
| 2608 | enc = copy.input_encoding = encoding or self.input_encoding |
| 2609 | copy.recode_unicode = False |
| 2610 | for key, value in self.allitems(): |
| 2611 | copy.append(self._fix(key, enc), self._fix(value, enc)) |
| 2612 | return copy |
| 2613 | |
| 2614 | def getunicode(self, name, default=None, encoding=None): |
| 2615 | """ Return the value as a unicode string, or the default. """ |
| 2616 | try: |
| 2617 | return self._fix(self[name], encoding) |
| 2618 | except (UnicodeError, KeyError): |
| 2619 | return default |
| 2620 | |
| 2621 | def __getattr__(self, name, default=unicode()): |
| 2622 | # Without this guard, pickle generates a cryptic TypeError: |
| 2623 | if name.startswith('__') and name.endswith('__'): |
| 2624 | return super(FormsDict, self).__getattr__(name) |
| 2625 | return self.getunicode(name, default=default) |
| 2626 | |
| 2627 | class HeaderDict(MultiDict): |
| 2628 | """ A case-insensitive version of :class:`MultiDict` that defaults to |