2012-07-19 185 views
1

我有一个用Twisted Web编写的前端Web服务器,它与另一个Web服务器进行连接。客户端将文件上传到我的前端服务器,然后将这些文件一起发送到后端服务器。我想接收上传的文件,然后在将文件发送到后端服务器之前立即向客户端发送响应。这样客户端在得到响应之前不必等待两次上传。Twisted 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

回答

1

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

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

不是传递整个请求到你的线程快速测试会试图只是请求的内容传递到您的线程:

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

感谢您的建议,即工作! – user1536676 2012-07-19 15:13:01