Python: How do I get key/value pairs from the BaseHTTPRequestHandler HTTP POST handler? Python: How do I get key/value pairs from the BaseHTTPRequestHandler HTTP POST handler? python python

Python: How do I get key/value pairs from the BaseHTTPRequestHandler HTTP POST handler?


def do_POST(self):    ctype, pdict = cgi.parse_header(self.headers.getheader('content-type'))    if ctype == 'multipart/form-data':        postvars = cgi.parse_multipart(self.rfile, pdict)    elif ctype == 'application/x-www-form-urlencoded':        length = int(self.headers.getheader('content-length'))        postvars = cgi.parse_qs(self.rfile.read(length), keep_blank_values=1)    else:        postvars = {}    ...


I tried to edit the post and got rejected, so there's my version of this code that should work on Python 2.7 and 3.2:

from sys import version as python_versionfrom cgi import parse_header, parse_multipartif python_version.startswith('3'):    from urllib.parse import parse_qs    from http.server import BaseHTTPRequestHandlerelse:    from urlparse import parse_qs    from BaseHTTPServer import BaseHTTPRequestHandlerclass RequestHandler(BaseHTTPRequestHandler):    ...    def parse_POST(self):        ctype, pdict = parse_header(self.headers['content-type'])        if ctype == 'multipart/form-data':            postvars = parse_multipart(self.rfile, pdict)        elif ctype == 'application/x-www-form-urlencoded':            length = int(self.headers['content-length'])            postvars = parse_qs(                    self.rfile.read(length),                     keep_blank_values=1)        else:            postvars = {}        return postvars    def do_POST(self):        postvars = self.parse_POST()        ...    ...