22

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]);
Lightness Races in Orbit
387k77 gold badges672 silver badges1.1k bronze badges
asked Jan 23, 2010 at 0:29
2
  • 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? Commented 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. Commented Jan 23, 2010 at 18:17

1 Answer 1

26

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.

answered Jan 23, 2010 at 20:11
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.