summaryrefslogtreecommitdiff
path: root/tests/cgiapp_data/form.cgi
blob: c4c562d2e7e017f685bd193b8afdc6606a68181a (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
#!/usr/bin/env python

from __future__ import print_function

import cgi
import six

print('Content-type: text/plain')
print('')

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)
print('Content: %s' % form['up'].file.read())