Skip to content

Instantly share code, notes, and snippets.

@nickcheng
Created July 9, 2018 14:14
Show Gist options
  • Save nickcheng/5e8e0f19df84280bd12d088dee1b4748 to your computer and use it in GitHub Desktop.
Save nickcheng/5e8e0f19df84280bd12d088dee1b4748 to your computer and use it in GitHub Desktop.
#Python: How do I get key/value pairs from the BaseHTTPRequestHandler HTTP POST handler?
from sys import version as python_version
from cgi import parse_header, parse_multipart
if python_version.startswith('3'):
from urllib.parse import parse_qs
from http.server import BaseHTTPRequestHandler
else:
from urlparse import parse_qs
from BaseHTTPServer import BaseHTTPRequestHandler
class 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()
...
...
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment