Twisted上传多个文件密钥错误

时间:2017-11-22 16:54:50

标签: python-3.x twisted

我试图在Python 3.6中编写一个Twisted Webserver,它可以上传多个文件,但对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 个答案:

答案 0 :(得分:1)

Python 3+中的

FieldStorage返回一个带字符串的字典,而不是字符串。所以你必须访问这样的密钥:

postfile[ b"file" ]

请注意,该密钥附加了b""。如果你是Python的新手并且不知道Python 3和2字符串之间的变化,那会有点混乱。

我回答了similar question一段时间但是无法在Python 3.4上正常工作但我不记得究竟什么都行不通。希望您不要使用3.6。

遇到任何问题