test: stop using deprecated cgi module for multipart post parsing

Python 3.13 removes the cgi module and recommends using EmailMessage for
parsing a multipart section. This is a bit trickier as it needs a full
message with original Content-Type header and boundary.

As this runs inside our testvm we can't rely on for example the
`multipart` module.
This commit is contained in:
Jelle van der Waa 2024-04-18 12:35:00 +02:00 committed by Jelle van der Waa
parent 41ed7872c6
commit 9d94d911f2
1 changed files with 16 additions and 10 deletions

View File

@ -1,7 +1,9 @@
#!/usr/bin/python3
# export uReport_URL="http://localhost:12345"
import cgi
import email
import email.parser
import email.policy
import json
import sys
from http.server import BaseHTTPRequestHandler, HTTPServer
@ -32,21 +34,25 @@ class Handler(BaseHTTPRequestHandler):
self.wfile.write(json.dumps(response, indent=2).encode('UTF-8'))
def do_POST(self):
form = cgi.FieldStorage(
fp=self.rfile,
headers=self.headers,
environ={
'REQUEST_METHOD': 'POST',
'CONTENT_TYPE': self.headers['Content-Type'],
}
)
content_length = int(self.headers.get('content-length', 0))
data = self.rfile.read(content_length)
# Without the cgi module, we need to massage the data to form a valid message
p = email.parser.BytesFeedParser(policy=email.policy.HTTP)
p.feed('Content-Type: {}\r\n'.format(self.headers.get('content-type', '')).encode('utf-8'))
p.feed('\r\n'.encode('utf-8'))
p.feed(data)
m = p.close()
assert m.is_multipart(), "not a multipart message"
parts = list(m.iter_parts())
json_str = parts[0].get_payload()
self.send_response(202)
self.send_header('Content-Type', 'application/json')
self.send_header('Connection', 'close')
self.end_headers()
json_str = form['file'].file.read()
try:
# just check that it's a JSON
json.loads(json_str)