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-
| 1892 | |
| 1893 | |
| 1894 | class FormsDict(MultiDict): |
| 1895 | ''' This :class:`MultiDict` subclass is used to store request form data. |
| 1896 | Additionally to the normal dict-like item access methods (which return |
| 1897 | unmodified data as native strings), this container also supports |
| 1898 | attribute-like access to its values. Attributes are automatically de- |
| 1899 | or recoded to match :attr:`input_encoding` (default: 'utf8'). Missing |
| 1900 | attributes default to an empty string. ''' |
| 1901 | |
| 1902 | #: Encoding used for attribute values. |
| 1903 | input_encoding = 'utf8' |
| 1904 | #: If true (default), unicode strings are first encoded with `latin1` |
| 1905 | #: and then decoded to match :attr:`input_encoding`. |
| 1906 | recode_unicode = True |
| 1907 | |
| 1908 | def _fix(self, s, encoding=None): |
| 1909 | if isinstance(s, unicode) and self.recode_unicode: # Python 3 WSGI |
| 1910 | return s.encode('latin1').decode(encoding or self.input_encoding) |
| 1911 | elif isinstance(s, bytes): # Python 2 WSGI |
| 1912 | return s.decode(encoding or self.input_encoding) |
| 1913 | else: |
| 1914 | return s |
| 1915 | |
| 1916 | def decode(self, encoding=None): |
| 1917 | ''' Returns a copy with all keys and values de- or recoded to match |
| 1918 | :attr:`input_encoding`. Some libraries (e.g. WTForms) want a |
| 1919 | unicode dictionary. ''' |
| 1920 | copy = FormsDict() |
| 1921 | enc = copy.input_encoding = encoding or self.input_encoding |
| 1922 | copy.recode_unicode = False |
| 1923 | for key, value in self.allitems(): |
| 1924 | copy.append(self._fix(key, enc), self._fix(value, enc)) |
| 1925 | return copy |
| 1926 | |
| 1927 | def getunicode(self, name, default=None, encoding=None): |
| 1928 | ''' Return the value as a unicode string, or the default. ''' |
| 1929 | try: |
| 1930 | return self._fix(self[name], encoding) |
| 1931 | except (UnicodeError, KeyError): |
| 1932 | return default |
| 1933 | |
| 1934 | def __getattr__(self, name, default=unicode()): |
| 1935 | # Without this guard, pickle generates a cryptic TypeError: |
| 1936 | if name.startswith('__') and name.endswith('__'): |
| 1937 | return super(FormsDict, self).__getattr__(name) |
| 1938 | return self.getunicode(name, default=default) |
| 1939 | |
| 1940 | class HeaderDict(MultiDict): |
| 1941 | """ A case-insensitive version of :class:`MultiDict` that defaults to |