I'm converting a Python2.6 app into a Python3 app and I'm getting stuck with the server. I've managed to get it serving up GET requests just fine but POST continues to elude me. Here is what I started with in 2.6 that worked but in 3.x the normal server does not handle POST requests. From my reading of the Python manual it appears that I must use a CGI server class instead and also map the scripts to that directory. I'd rather not have to do this but I cannot find another way. Am I missing something?
def do_POST(self):
ctype, pdict = cgi.parse_header(self.headers.get('content-type'))
if ctype == 'multipart/form-data':
query = cgi.parse_multipart(self.rfile, pdict)
self.send_response(301)
self.end_headers()
upfilecontent = query.get('upfile')
print("filecontent", upfilecontent[0])
self.wfile.write("<HTML>POST OK.<BR><BR>");
self.wfile.write(upfilecontent[0]);
-
In what way does not the normal server handle post requests in Python 3, that it does in Python 2? Can you explain what the problem is?Lennart Regebro– Lennart Regebro2010年01月23日 08:13:25 +00:00Commented Jan 23, 2010 at 8:13
-
Yeah, it won't impliment a do_post() function while the one from Python2 will. There are no solid code examples of how to overcome it in the Python documentation and Googling for it hasn't helped either.Teifion– Teifion2010年01月23日 18:17:28 +00:00Commented Jan 23, 2010 at 18:17
1 Answer 1
After poking and a few more hours of googling I've found the following works.
def do_POST(self):
length = int(self.headers['Content-Length'])
post_data = urllib.parse.parse_qs(self.rfile.read(length).decode('utf-8'))
# You now have a dictionary of the post data
self.wfile.write("Lorem Ipsum".encode("utf-8"))
I'm surprised at how easy this was.