【问题标题】:Python 2 do_POST http.server multipart/formdata to Python 3Python 2 do_POST http.server multipart/formdata 到 Python 3
【发布时间】:2016-05-21 20:38:47
【问题描述】:

问题:试图将讲师的 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 存储库、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!')

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

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

【问题讨论】:

    标签: python forms python-2.7 python-3.x http-post


    【解决方案1】:

    我的解决方案

    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') 的“名称”之前添加一个空格。但是,嘿!有效!

    更新:终于弄明白了

    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 全栈基础课程的束缚!!

    【讨论】:

    • 你能解释一下为什么你创建了一个 pdict['boundary'] 并解释一下关于 Python3 更改的其他更改吗?
    【解决方案2】:

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

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

       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
    

    【讨论】:

      猜你喜欢
      • 2016-08-22
      • 1970-01-01
      • 2016-07-13
      • 2014-11-07
      • 1970-01-01
      • 2019-09-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多