classification
Title: cgi.parse() does not work with multipart POST requests.
Type: behavior Stage: patch review
Components: Library (Lib) Versions: Python 3.9, Python 3.8, Python 3.7, Python 3.6, Python 3.5
process
Status: open Resolution:
Dependencies: Superseder:
Assigned To: Nosy List: sangh
Priority: normal Keywords: patch

Created on 2020-03-21 17:23 by sangh, last changed 2020-03-24 01:03 by sangh.

Pull Requests
URL Status Linked Edit
PR 19130 open sangh, 2020-03-24 01:03
Messages (1)
msg364762 - (view) Author: San (sangh) * Date: 2020-03-21 17:23
The cgi.parse stdlib function works in most cases but never works when given a multipart/form-data POST request because it does not set up pdict in a way cgi.parse_multipart() likes (boundary as bytes (not str) and including content length).




$ pwd
/tmp
$
$ /tmp/cpython/python --version
Python 3.9.0a4+
$
$ cat cgi-bin/example.cgi
#!/tmp/cpython/python
import sys, cgi
query_dict = cgi.parse()
write = sys.stdout.buffer.write
write("Content-Type: text/plain; charset=utf-8\r\n\r\n".encode("ascii"))
write(f"Worked, query dict is {query_dict}.\n".encode())
$
$ /tmp/cpython/python -m http.server --cgi & sleep 1
[1] 30201
Serving HTTP on 0.0.0.0 port 8000 (http://0.0.0.0:8000/) ...
$
$ # GET (url-encoded) requests work:
$ curl localhost:8000/cgi-bin/example.cgi?example_key=example_value
127.0.0.1 - - [20/Mar/2020 23:33:48] "GET /cgi-bin/example.cgi?example_key=example_value HTTP/1.1" 200 -
Worked, query dict is {'example_key': ['example_value']}.
$
$ # POST (multipart) requests do not:
$ curl localhost:8000/cgi-bin/example.cgi -F example_key=example_value
127.0.0.1 - - [20/Mar/2020 23:34:15] "POST /cgi-bin/example.cgi HTTP/1.1" 200 -
Traceback (most recent call last):
  File "/tmp/cgi-bin/example.cgi", line 3, in <module>
    query_dict = cgi.parse()
  File "/tmp/cpython/Lib/cgi.py", line 159, in parse
    return parse_multipart(fp, pdict)
  File "/tmp/cpython/Lib/cgi.py", line 201, in parse_multipart
    boundary = pdict['boundary'].decode('ascii')
AttributeError: 'str' object has no attribute 'decode'
127.0.0.1 - - [20/Mar/2020 23:34:16] CGI script exit status 0x100
$
$ $EDITOR /tmp/cpython/Lib/cgi.py
$
$ # After changing cgi.parse POST (multipart) requests work:
$ curl localhost:8000/cgi-bin/example.cgi -F example_key=example_value
127.0.0.1 - - [20/Mar/2020 23:35:10] "POST /cgi-bin/example.cgi HTTP/1.1" 200 -
Worked, query dict is {'example_key': ['example_value']}.
$
History
Date User Action Args
2020-03-24 01:03:00sanghsetkeywords: + patch
stage: patch review
pull_requests: + pull_request18492
2020-03-21 17:23:48sanghcreate