2015-09-10 44 views

回答

3

您可以覆蓋SimpleHTTPServer模塊中的請求處理程序。我把一個片段放在下面

from __future__ import print_function 
import os 
import SimpleHTTPServer 
import SocketServer 


class MySimpleHTTPRequestHandler(SimpleHTTPServer.SimpleHTTPRequestHandler): 

    def do_GET(self): 
     """Serve a GET request.""" 
     f = self.send_head() 
     if f: 
      try: 
       self.copyfile(f, self.wfile) 
      finally: 
       if(os.path.isfile(self.translate_path(self.path))): 
        print("Log this download:", self.translate_path(self.path)) 
       f.close() 

PORT = 8000 

Handler = MySimpleHTTPRequestHandler 

httpd = SocketServer.TCPServer(("", PORT), Handler) 

print("serving at port", PORT) 
httpd.serve_forever() 
+1

只是要明確一點:即使客戶端斷開連接不完整的下載,這會觸發'finally'部分,對吧? –

+0

是的你是對的。如果請求完全由用戶接收而不中斷,似乎很難輕易識別。 – ozy