diff options
author | Nils Philippsen <nils@redhat.com> | 2015-08-20 10:30:28 +0200 |
---|---|---|
committer | Nils Philippsen <nils@redhat.com> | 2015-08-20 10:30:28 +0200 |
commit | b2cd7cf584e3b1c64b248b6864cbc7cec15ca987 (patch) | |
tree | bd0c1a94cc94455465a7387f2a54cfea7ac3d934 | |
parent | 5c06ca6a99c892ac4d856002a9b2fd2dcbb64778 (diff) | |
download | paste-git-b2cd7cf584e3b1c64b248b6864cbc7cec15ca987.tar.gz |
Python 3: add workarounds for cgi.FieldStorage
cgi.FieldStorage keeps some keys as str, some as the repr() of the
byte-encoded key, duh.
Fixes (well...): tests.test_cgiapp.test_form
-rwxr-xr-x | tests/cgiapp_data/form.cgi | 59 |
1 files changed, 58 insertions, 1 deletions
diff --git a/tests/cgiapp_data/form.cgi b/tests/cgiapp_data/form.cgi index 2181998..c4c562d 100755 --- a/tests/cgiapp_data/form.cgi +++ b/tests/cgiapp_data/form.cgi @@ -1,11 +1,68 @@ #!/usr/bin/env python +from __future__ import print_function + import cgi +import six print('Content-type: text/plain') print('') -form = cgi.FieldStorage() +if six.PY3: + # Python 3: cgi.FieldStorage keeps some field names as unicode and some as + # the repr() of byte strings, duh. + + class FieldStorage(cgi.FieldStorage): + + def _key_candidates(self, key): + yield key + + try: + # assume bytes, coerce to str + try: + yield key.decode(self.encoding) + except UnicodeDecodeError: + pass + except AttributeError: + # assume str, coerce to bytes + try: + yield key.encode(self.encoding) + except UnicodeEncodeError: + pass + + def __getitem__(self, key): + + superobj = super(FieldStorage, self) + + error = None + + for candidate in self._key_candidates(key): + if isinstance(candidate, bytes): + # ouch + candidate = repr(candidate) + try: + return superobj.__getitem__(candidate) + except KeyError as e: + if error is None: + error = e + + # fall through, re-raise the first KeyError + raise error + + def __contains__(self, key): + superobj = super(FieldStorage, self) + + for candidate in self._key_candidates(key): + if superobj.__contains__(candidate): + return True + return False + +else: # PY2 + + FieldStorage = cgi.FieldStorage + + +form = FieldStorage() print('Filename: %s' % form['up'].filename) print('Name: %s' % form['name'].value) |