2012-07-19 203 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