代码之家  ›  专栏  ›  技术社区  ›  bits

Twisted upload多文件密钥错误

  •  1
  • bits  · 技术社区  · 8 年前

    我正试图用Python 3.6编写一个Twisted Web服务器,它可以上载多个文件,但对于Python和Web这两种东西来说都是相当新的,我遇到了一个我不理解的问题,我也没有找到任何与多文件上载相关的好例子。

    通过以下代码,我得到

    from twisted.web import server, resource
    from twisted.internet import reactor, endpoints
    import cgi
    
    
    class Counter(resource.Resource):
        isLeaf = True
        numberRequests = 0
    
        def render_GET(self, request):
            print("GET " + str(self.numberRequests))
            self.numberRequests += 1
            # request.setHeader(b"content-type", b"text/plain")
            # content = u"I am request #{}\n".format(self.numberRequests)
            content = """<html>
            <body>
            <form enctype="multipart/form-data" method="POST">
                Text: <input name="text1" type="text" /><br />
                File: <input name="file1" type="file" multiple /><br />
                <input type="submit" />
            </form>
            </body>
            </html>"""
            print(request.uri)
    
    
            return content.encode("ascii")
    
        def render_POST(selfself, request):
            postheaders = request.getAllHeaders()
            try:
                postfile = cgi.FieldStorage(
                    fp=request.content,
                    headers=postheaders,
                    environ={'REQUEST_METHOD': 'POST',
                            # 'CONTENT_TYPE': postheaders['content-type'], Gives builtins.KeyError: 'content-type'
                             }
                )
            except Exception as e:
                print('something went wrong: ' + str(e))
    
            filename = postfile["file"].filename #file1 tag also does not work
            print(filename)
    
            file = request.args["file"][0] #file1 tag also does not work
    
    
    
    endpoints.serverFromString(reactor, "tcp:1234").listen(server.Site(Counter()))
    
    reactor.run()
    

    错误日志

    C:\Users\theuser\AppData\Local\conda\conda\envs\py36\python.exe C:/Users/theuser/PycharmProjects/myproject/twweb.py
    GET 0
    b'/'
    # My comment POST starts here
    Unhandled Error
    Traceback (most recent call last):
      File "C:\Users\theuser\AppData\Local\conda\conda\envs\py36\lib\site-packages\twisted\web\http.py", line 1614, in dataReceived
        finishCallback(data[contentLength:])
      File "C:\Users\theuser\AppData\Local\conda\conda\envs\py36\lib\site-packages\twisted\web\http.py", line 2029, in _finishRequestBody
        self.allContentReceived()
      File "C:\Users\theuser\AppData\Local\conda\conda\envs\py36\lib\site-packages\twisted\web\http.py", line 2104, in allContentReceived
        req.requestReceived(command, path, version)
      File "C:\Users\theuser\AppData\Local\conda\conda\envs\py36\lib\site-packages\twisted\web\http.py", line 866, in requestReceived
        self.process()
    --- <exception caught here> ---
      File "C:\Users\theuser\AppData\Local\conda\conda\envs\py36\lib\site-packages\twisted\web\server.py", line 195, in process
        self.render(resrc)
      File "C:\Users\theuser\AppData\Local\conda\conda\envs\py36\lib\site-packages\twisted\web\server.py", line 255, in render
        body = resrc.render(self)
      File "C:\Users\theuser\AppData\Local\conda\conda\envs\py36\lib\site-packages\twisted\web\resource.py", line 250, in render
        return m(request)
      File "C:/Users/theuser/PycharmProjects/myproject/twweb.py", line 42, in render_POST
        filename = postfile["file"].filename #file1 tag also does not work
      File "C:\Users\theuser\AppData\Local\conda\conda\envs\py36\lib\cgi.py", line 604, in __getitem__
        raise KeyError(key)
    builtins.KeyError: 'file'
    

    我不知道如何获取文件,以便在render_POST中提交表单后保存上传的文件。此帖子 SO 似乎没有这个问题。最终的应用程序应该能够为多个用户执行异步操作,但在此之前,我很乐意只让一个简单的应用程序工作。

    在Windows 10和Python 3.6上使用conda

    1 回复  |  直到 8 年前
        1
  •  1
  •   notorious.no    8 年前

    FieldStorage 在Python中,3+返回一个dict,其中键是字节,而不是字符串。因此,您必须访问以下密钥:

    postfile[ b"file" ]
    

    请注意,该键附加了 b"" . 如果您是Python新手,并且不知道Python 3和2字符串之间的变化,那么这有点令人困惑。

    我还回答了一个 similar question 前一段时间,但无法使其在Python 3.4上正常工作,但我记不起到底是什么不起作用了。希望您在使用3.6时不会遇到任何问题。