2017-04-24 193 views
0

在我的情況下,我有Django 1.11服務器充當代理。當您從瀏覽器中點擊「下載」時,它會向django代理髮送請求,從其他服務器下載文件並對其進行處理,然後將其發送到瀏覽器以允許用戶下載。我的代理通過塊下載並處理文件塊。 如何在瀏覽器準備就緒時向瀏覽器發送塊,以便用戶最終下載單個文件?Django 1.11通過塊下載文件塊

在實踐中,我必須讓你下載一個尚未準備好的文件,比如流。

def my_download(self, res) 

    # some code 
    file_handle = open(local_path, 'wb', self.chunk_size) 

    for chunk in res.iter_content(self.chunk_size): 
     i = i+1 
     print("index: ", i, "/", chunks) 
     if i > chunks-1: 
      is_last = True 

     # some code on chunk 

     # Here, instead of saving the chunk locally, I would like to allow it to download it directly. 
     file_handle.write(chunk) 
    file_handle.close() 

    return True 

謝謝你,問候。

+0

我終於找到了答案在這裏:https://stackoverflow.com/questions/38514919/django-stream-request-from-external-site-as-received 這個問題實際上是一個dupplicate –

+0

是的,這裏https://stackoverflow.com/questions/48949022/django-filewrapper-memory-error-serving-big-files-how-to-stream/48949959#48949959 – trinchet

+0

而在這裏:https:// stackoverflow。 com/questions/8600843/serving-large-files-with-high-loads-in-django?answertab = votes#tab-top –

回答

2

這個問題應該被標記爲這篇文章的重複:Serving large files (with high loads) in Django

應儘量您在SO創建一個問題之前找到答案,請!

本質的答案被包含在Django的文檔:"Streaming Large CSV files"例如我們會申請對上述問題成例如:


您可以使用Django的StreamingHttpResponse和Python的wsgiref.util.FileWrapper服務於塊大文件effectivelly並且不需要將其加載到內存中。

def my_download(request): 
    file_path = 'path/to/file' 
    chunk_size = DEFINE_A_CHUNK_SIZE_AS_INTEGER 
    filename = os.path.basename(file_path) 

    response = StreamingHttpResponse(
     FileWrapper(open(file_path, 'rb'), chunk_size), 
     content_type="application/octet-stream" 
    ) 
    response['Content-Length'] = os.path.getsize(file_path)  
    response['Content-Disposition'] = "attachment; filename=%s" % filename 
    return response 

現在,如果你想要一些處理應用到文件塊逐塊,你可以利用FileWrapper's產生的迭代器:

放置在一個函數的塊處理代碼MUST返回大塊:

def chunk_processing(chunk): 
    # Process your chunk here 
    # Be careful to preserve chunk's initial size. 
    return processed_chunk 

現在將函數應用於StreamingHttpResponse

response = StreamingHttpResponse(
    (
     process_chunk(chunk) 
     for chunk in FileWrapper(open(file_path, 'rb'), chunk_size 
    ),content_type="application/octet-stream" 
) 
+0

我正在尋找回答幾分鐘後才發現這個問題(這就是爲什麼我提出了獎勵)。其實「服務大文件」並不是我能想到的唯一用途,所以我沒有考慮像那樣尋找它 –

+0

@LuisSieira我編輯了我的答案,包含了OP最初問題的一部分答案。儘管如此,這不是一個重複的問題... –

+0

是的,它應該像這樣標記,但作爲解決前面問題答案的問題的重新表述很有用。 –