[Django] technology blog files downloaded achieve

Development team in the development process, will inevitably encounter some difficulties or problems, but they eventually find a way to overcome. We believe that this experience is necessary to record, so there is a [technical] blog.


Django files downloaded achieve

1. Background

In VisualPytorch project was the need to provide a file download function. Initially I think there are about three kinds of programs

  • Directly to the front page of the string to the file, the completion of the client.

The program information found through the search-origin policy different browsers and security policy are not the same, difficult to give up.

  • On the server to open a ftp server system to provide file services.

This is the idea of ​​the beginning, and later that the current performance of the server itself is limited based on actual demand, coupled with the current needs of the project file is relatively simple, no complicated file services.

  • Generating at the server files directly fixed directory, after transmission through the pack in the form of http stream

And ultimately the method employed, relatively simple and easy to implement.

2, Django backend file packaged with download

About bale file, use the python zipfile package when implementing this

zipf = zipfile.ZipFile("project_VisualPytorch.zip", 'w',zipfile.ZIP_DEFLATED)

For details on the use of zipfile be found https://docs.python.org/3/library/zipfile.html

Background server through the response object Http configured to transmit data to the front end, for large file transfers, it is recommended to use StreamingHttpResponse or FileResponse frame configuration Django response object.

StreamingHttpResponse using streaming files, the parameter is an iterator, file fragmentation transfer, to achieve the following

response = StreamingHttpResponse(file_iterator("project_VisualPytorch.zip"))
response['Content-Type'] = 'application/zip'
response['Content-Disposition'] = 'attachment;filename="project_VisualPytorch.zip"'
return response

Construction of the iterator as follows

def file_iterator(file_name, chunk_size=512):
    with open(file_name, 'rb') as f:
        while True:
            c = f.read(chunk_size)
            if c:
                yield c
            else:
                break

Here fragment size 512 is provided.

FileResponse is a subclass StreamingHttpResponse using caching techniques, in some cases better than the parent class.

Guess you like

Origin www.cnblogs.com/1606-huluwa/p/10990956.html