Several ways to Django download files

Source: Internet
Author: User
Tags readfile wrapper

Turn from: http://blog.sciencenet.cn/blog-47522-664541.html

Several ways to Django download files

from:http://oldj.net/article/django-big-file-response/

from:http://www.douban.com/group/topic/17856825/

From:http://hi.baidu.com/acmtiger/blog/item/e4e5b1874f529bb10df4d2b4.html

1, direct Read/yeild return to the client

However, there are no corresponding methods in Django. One solution is to generate all the content that will be delivered in memory, and then pass in the HttpResponse at once, for example:
F =open (filename)
data = F.read ()
F.close ()
#以下设置项是为了下载任意类型文件
Response = HttpResponse (data,mimetype= ' Application/octet-stream ')
response[' content-disposition '] = ' attachment; filename=%s '%filename
return response

This is the easiest way to handle it, but there is a big problem, if the file is very large, it can take up a lot of memory and even cause the server to crash.

However, Django developers should also take this into account, as mentioned in the official document, you can pass an iterator to HttpResponse, and there is a page on StackOverflow that discusses the problem. Based on the contents of these two pages, the above problem of downloading large files can be resolved as follows:

Def bigfileview (Request):
    # do something ...
 
    def readFile (FN, buf_size=262144):
        f = open (FN, RB)
        while True:
             C = f.read (buf_size)
             if C:
                 Yield C
            else:
                 Break
         f.close ()
 
    file_name = "Big_file.txt"
    Response = HttpResponse (ReadFile (file_name))
 
    return response  

Although this is not the same as flush in other languages, and not every time yield the client receives the appropriate content (possibly because of the server or the client buffer), this approach does solve the problem of large file or large content downloads. After testing, using this method to download large files, the server's memory footprint is almost unchanged.

2. Configure users to download files directly

After urls.py file, configure the corresponding download address
e.g.,
...
(R ' ^download/(?) p<path>.*) $ ', ' Django.views.static.serve ', {' document_root ': Your_download_path, ' show_indexes ': True}),
...
Http://xxxxx/download/a.txt

3, download large files and compressed zip file

01.import OS, Tempfile, ZipFile
02.from django.http Import HttpResponse
03.from django.core.servers.basehttp Import FileWrapper
04.
05.
06.def Send_file (Request):
07. "" "
"Send a" file through Django without loading the whole file into
Memory at once. The FileWrapper'll turn the "file object into"
Iterator for chunks of 8KB.
11. "" "
filename = __file__ # Select your file here.
Wrapper = filewrapper (file (filename))
Response = HttpResponse (wrapper, content_type= ' Text/plain ')
response[' content-length ' = os.path.getsize (filename)
return response
17.
18.
19.def Send_zipfile (Request):
20. "" "
Create a ZIP file on disk and transmit it in chunks of 8KB,
Without loading the whole file into memory. A similar approach can
Used for large dynamic PDF files.
24. "" "
temp = Tempfile. Temporaryfile ()
Archive = ZipFile. ZipFile (temp, ' w ', ZipFile.) zip_deflated)
For index in range (10):
filename = __file__ # Select your files here.
Archive.write (filename, ' file%d.txt '% index)
Archive.close ()
wrapper = FileWrapper (temp)
Response = HttpResponse (wrapper, content_type= ' Application/zip ')
response[' content-disposition '] = ' attachment; Filename=test.zip '
response[' content-length '] = Temp.tell ()
Temp.seek (0)
return response

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.