简体   繁体   中英

Python3 http.server POST example

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]);

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM