【问题标题】:Twisted web - Keep request data after responding to clientTwisted web - 在响应客户端后保留请求数据
【发布时间】:2012-07-18 05:15:38
【问题描述】:

我有一个用 Twisted Web 编写的前端 Web 服务器,它与另一个 Web 服务器连接。客户端将文件上传到我的前端服务器,然后将文件发送到后端服务器。我想接收上传的文件,然后在将文件发送到后端服务器之前立即向客户端发送响应。这样,客户端就不必等待两次上传都发生后才得到响应。

我正在尝试通过在单独的线程中开始上传到后端服务器来做到这一点。问题是,在向客户端发送响应后,我不再能够从Request 对象访问上传的文件。这是一个例子:

class PubDir(Resource):

    def render_POST(self, request):
        if request.args["t"][0] == 'upload':
            thread.start_new_thread(self.upload, (request,))

        ### Send response to client while the file gets uploaded to the back-end server:
        return redirectTo('http://example.com/uploadpage')

    def upload(self, request):
        postheaders = request.getAllHeaders()
        try:
            postfile = cgi.FieldStorage(
                fp = request.content,
                headers = postheaders,
                environ = {'REQUEST_METHOD':'POST',
                         'CONTENT_TYPE': postheaders['content-type'],
                        }
                )
        except Exception as e:
            print 'something went wrong: ' + str(e)

        filename = postfile["file"].filename

        file = request.args["file"][0]

        #code to upload file to back-end server goes here...

当我尝试这个时,我收到一个错误:I/O operation on closed file

【问题讨论】:

    标签: python file-upload upload twisted twisted.web


    【解决方案1】:

    在完成请求对象之前,您需要将文件实际复制到内存中的缓冲区或磁盘上的临时文件中(重定向时会发生这种情况)。

    因此,您正在启动线程并将请求对象交给它,它可能正在打开与后端服务器的连接并在您重定向完成请求并关闭任何关联的临时文件时开始复制,而您遇到了麻烦。

    快速测试不是将整个请求传递给您的线程,而是尝试将请求的内容传递给您的线程:

    thread.start_new_thread(self.upload, (request.content.read(),))
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-08-14
      • 2018-10-12
      • 1970-01-01
      • 2021-08-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-02-01
      相关资源
      最近更新 更多