summaryrefslogtreecommitdiff
path: root/tests/cgiapp_data/form.cgi
blob: 5ad8f68b8005bc25ad9c126309c5f3df139a67e0 (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
70
71
72
73
74
75
76
#!/usr/bin/env python

from __future__ import print_function

import sys

# Quiet warnings in this CGI so that it does not upset tests.
if not sys.warnoptions:
    import warnings
    warnings.simplefilter("ignore")

# TODO: cgi is deprecated and will go away in Python 3.13.
import cgi

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

if sys.version_info.major >= 3:
    # 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())