2012-09-13 28 views
0

我正在構建一個私人文件上傳站點。 Alice上傳一個文件,Bob下載它。Django:讓用戶下載一個大文件

Alice和Bob以外的人不應該有權訪問。我首先想給文件一個複雜的名稱(http://domain/download/md5sum.zip),但我想要一個到期的鏈接。所以像http://domain/download/tempkey/aaa123/file.zip。這會讓我更好地控制文件下載和日誌記錄。

我發現這個:https://stackoverflow.com/a/2900646。它建議如下:

class RequestHandler(BaseHTTPServer.BaseHTTPRequestHandler): 

    def do_GET(self): 
     # The URL the client requested 
     print self.path 

     # analyze self.path, map the local file location... 

     # open the file, load the data 
     with open('test.py') as f: data = f.read() 

     # send the headers 
     self.send_response(200) 
     self.send_header('Content-type', 'application/octet-stream') # you may change the content type 
     self.end_headers() 
     # If the file is not found, send error code 404 instead of 200 and display a message accordingly, as you wish. 

     # wfile is a file-like object. writing data to it will send it to the client 
     self.wfile.write(data) 

但是,我怎麼得到這個在Django工作?一個views函數應該返回一個HTTPResponse對象,這是不行的。

+2

請勿使用django進行文件下載處理,而應使用Apache x-sendfile。 – iMom0

回答

4

不推薦使用Django來下載大文件。通常你會有一個前端多路複用器,比如NginX,並且只使用Django來驗證文件。

然後,如果下載通過驗證,您將向複用器發出信號。對於NginX,你可以設置一個特殊的頭文件(「X-Accel-Redirect」)來指向本地文件的真實位置。 Django只會服務幾個字節,所有的繁重工作都將由NginX處理;同時原來的URL將是Django的URL,所以不可能繞過安全。

參見:http://wiki.nginx.org/X-accel

您可以在這裏找到有關如何爲靜態文件的註釋(可擴展身份驗證)

https://docs.djangoproject.com/en/dev/howto/static-files/

但隨着網頁說,這是「一個快速和骯髒幫手視圖「不適用於生產或高流量的網站。這不是Django設計的目的,即使可以也可以。