Django StreamingHttpResponse: Stream Large Files Efficiently
Here's an example of using 'StreamingHttpResponse' in Django to stream a large file:
from django.http import StreamingHttpResponse
import os
def stream_file(request):
filepath = '/path/to/large/file'
chunk_size = 8192
def file_iterator(filepath, chunk_size):
with open(filepath, 'rb') as f:
while True:
data = f.read(chunk_size)
if not data:
break
yield data
response = StreamingHttpResponse(file_iterator(filepath, chunk_size))
response['Content-Length'] = os.path.getsize(filepath)
response['Content-Disposition'] = 'attachment; filename='%s'' % os.path.basename(filepath)
return response
In this example, 'file_iterator()' is a generator function that reads the file in chunks of 'chunk_size' bytes and yields each chunk. The 'StreamingHttpResponse' is then created with the generator function as its content. The 'Content-Length' header is set to the size of the file, and the 'Content-Disposition' header is set to indicate that the file should be downloaded as an attachment with its original filename.
原文地址: https://www.cveoy.top/t/topic/mMhX 著作权归作者所有。请勿转载和采集!