Python 2 do_POST http.server multipart/formdata 至 Python 3

Python 2 do_POST http.server multipart/formdata to Python 3

问题:尝试将讲师的 python 2 代码翻译成 python 3
具体问题:无法从 python 3

中的表单访问消息字段

Instructor's Code Snippet From Udacity Full-Stack Foundations Course

def do_POST(self):
            try:
                self.send_response(301)
                self.send_header('Content-type', 'text/html')
                self.end_headers()
                ctype, pdict = cgi.parse_header(
                    self.headers.getheader('content-type'))
                if ctype == 'multipart/form-data':
                    fields = cgi.parse_multipart(self.rfile, pdict)
                    messagecontent = fields.get('message')
                output = ""
                output += "<html><body>"
                output += " <h2> Okay, how about this: </h2>"
                output += "<h1> %s </h1>" % messagecontent[0]
                output += '''<form method='POST' enctype='multipart/form-data' action='/hello'><h2>What would you like me to say?</h2><input name="message" type="text" ><input type="submit" value="Submit"> </form>'''
                output += "</body></html>"
                self.wfile.write(output)
                print output
            except:
                pass

在查阅了文档、github 存储库、Whosebug 帖子并花费了无数小时之后...我不知道如何在 python 3 中提取消息字段,例如 fields.get('message').

我的尝试

def do_POST(self):
            try:
                length = int(self.headers['Content-Length'])
                print(self.headers['Content-Type'])
                self.send_response(301)
                self.send_header('Content-type', 'text/html')
                self.end_headers()
                post_data = parse_qs(self.rfile.read(length).decode('utf-8'))
                self.wfile.write("Lorem Ipsum".encode("utf-8"))
                ctype, pdict = cgi.parse_header(self.headers.getheader('content-type'))
                if ctype == 'multipart/form-data':
                    fields = cgi.parse_multipart(self.rfile, pdict)
                    messagecontent = fields.get('message')
    
                output = ''
                output += '<html><body>'
                output += '<h2> Okay, how about this: </h2>'
                output += '<h1> %s </h1>' % messagecontent[0]
                # You now have a dictionary of the post data
    
    
                output += "<form method='POST' enctype='multipart/form-data' action='/hello'><h2>What would you like me to say?</h2><input name='message' type='text'><input type='submit' value='Submit'></form>"
                output += '</html></body>'
                self.wfile.write(output.encode('utf-8'))
    
            except:
                print('Error!')

我的 post_data 变量是一个字典,但我找不到提取我在表单中输入的 'hi' 消息的方法。我也不确定这是否是从表单中提取数据的正确方法。

>>> post_data
{' name': ['"message"\r\n\r\nhi\r\n------WebKitFormBoundarygm0MsepKJXVrBubX--\r\n']}

我的解决方案

def do_POST(self):
            try:
                length = int(self.headers['Content-Length'])
                self.send_response(301)
                self.send_header('Content-type', 'text/html')
                self.end_headers()
                post_data = parse_qs(self.rfile.read(length).decode('utf-8'))
                messagecontent = post_data.get(' name')[0].split('\n')[2]
                output = ''
                output += '<html><body>'
                output += '<h2> Okay, how about this: </h2>'
                output += '<h1> %s </h1>' % messagecontent
                output += "<form method='POST' enctype='multipart/form-data' action='/hello'><h2>What would you like me to say?</h2><input name='message' type='text'><input type='submit' value='Submit'></form>"
                output += '</html></body>'
                self.wfile.write(output.encode('utf-8'))
            except:
                pass

如果有更好的方法,我也很想知道! 不知道为什么我必须在 post_data.get(' name') 中的 'name' 之前添加一个 space。但是,嘿!有效!

更新:终于想通了

def do_POST(self):
        self.send_response(301)
        self.send_header('Content-type', 'text/html')
        self.end_headers()
        ctype, pdict = cgi.parse_header(self.headers['Content-Type'])
        if ctype == 'multipart/form-data':
            pdict['boundary'] = bytes(pdict['boundary'], 'utf-8')
            fields = cgi.parse_multipart(self.rfile, pdict)
            messagecontent = fields.get('message')[0].decode('utf-8')
        output = ''
        output += '<html><body>'
        output += '<h2> Okay, how about this: </h2>'
        output += '<h1> %s </h1>' % messagecontent
        output += "<form method='POST' enctype='multipart/form-data' action='/hello'><h2>What would you like me to say?</h2><input name='message' type='text'><input type='submit' value='Submit'></form>"
        output += '</html></body>'
        self.wfile.write(output.encode('utf-8'))

使用它来摆脱 Udacity 全栈基础课程!!

在 posting(2019 年)时,我无法使您的代码正常工作。 检查 cgi 模块,parse_multipart 试图访问 pdict['CONTENT-LENGHT']

我的解决方案,工作@ post 时间:

   def do_POST(self):
    try:
        self.send_response(301)
        self.send_header('Content-type', 'text/html')
        self.end_headers()
        # HEADERS are now in dict/json style container
        ctype, pdict = cgi.parse_header(
            self.headers.get('content-type'))
        # boundary data needs to be encoded in a binary format


        if ctype == 'multipart/form-data':
            pdict['boundary'] = bytes(pdict['boundary'], "utf-8")
            pdict['CONTENT-LENGTH'] = self.headers.get('content-length')
            fields = cgi.parse_multipart(self.rfile, pdict)
            messagecontent = fields.get('message')

        output = ""
        output += "<html><body>"
        output += " <h2> Okay, how about this: </h2>"
        # decode it back into a string rather than byte string(b'stuff')
        output += "<h1> {} </h1>".format(messagecontent[0])
        output += '''<form method='POST' enctype='multipart/form-data' action='/hello'><h2>What would you like me to say?</h2><input name="message" type="text" ><input type="submit" value="Submit"> </form>'''
        output += "</body></html>"
        self.wfile.write(output.encode())
        print(output)

    except:
        raise