Twisted上传多个文件密钥错误

Twisted upload muliple files key error

我正在尝试在 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 中提交表单后上传的文件。这个postSO好像没有这个问题。最终的应用程序应该能够为多个用户执行此异步操作,但在此之前我很乐意让一个简单的应用程序正常工作。

在 Windows 10 和 Python 3.6

上使用 conda

FieldStorage in Python 3+ returns 一个字典,键为字节,而不是字符串。所以你必须像这样访问密钥:

postfile[ b"file" ]

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

不久前我也回答了一个 但无法让它在 Python 3.4 上正常工作,但我不记得到底是什么不起作用。希望您 运行 使用 3.6 时不会遇到任何问题。