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

Cle*_*mer 5 python forms http-post python-2.7 python-3.x

问题:尝试将讲师的python 2代码翻译为python 3
具体问题:无法从 python 3 中的表单访问消息字段

来自 Udacity 全栈基础课程的讲师代码片段

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
Run Code Online (Sandbox Code Playgroud)

在查找文档、github 存储库、stackoverflow 帖子并花费无数时间之后...我无法弄清楚如何在 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!')
Run Code Online (Sandbox Code Playgroud)

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

>>> post_data
{' name': ['"message"\r\n\r\nhi\r\n------WebKitFormBoundarygm0MsepKJXVrBubX--\r\n']}
Run Code Online (Sandbox Code Playgroud)

Cle*_*mer 3

我的解决方案

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
Run Code Online (Sandbox Code Playgroud)

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

更新:终于弄清楚了

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'))
Run Code Online (Sandbox Code Playgroud)

使用它可以摆脱 Udacity 全栈基础课程的困扰!