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

前端 未结 2 1843
清酒与你
清酒与你 2020-11-29 01:34

given the simplest HTTP server, how do I get post variables in a BaseHTTPRequestHandler?

from BaseHTTPServer import BaseHTTPRequestHandler, HTTPServer

class         


        
2条回答
  •  旧巷少年郎
    2020-11-29 01:59

    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_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()
            ...
    
        ...
    

提交回复
热议问题