How to download a dynamic file in django?
You can write a streamed response like you can see in the django docs
In your case it might do something like this with your file;
import csv
from django.http import StreamingHttpResponse
class Echo:
"""An object that implements just the write method of the file-like
interface.
"""
def write(self, value):
"""Write the value by returning it, instead of storing in a buffer."""
return value
def some_streaming_csv_view(request):
""" A view that streams a large CSV file. """
data = open(path,'r').readlines()
pseudo_buffer = Echo()
writer = csv.writer(pseudo_buffer)
response = StreamingHttpResponse(
(writer.writerow(row) for row in data),
content_type="text/csv"
)
response['Content-Disposition'] = 'attachment; filename="somefilename.csv"'
return response
Add the GET
param to your URL, because you're already adding it to the context and trying to read it back out;
<p><a href ="{% url 'download' %}?path={{ path|urlencode }}">Download (Filename)</a></p>
django download generated file
May be you should send the file as a chunk , which is memory efficient
import os
import mimetypes
from django.http import StreamingHttpResponse
from wsgiref.util import FileWrapper
def download_file(request):
the_file = open(file_path, "rb")
filename = os.path.basename(the_file)
chunk_size = 8192
response = StreamingHttpResponse(FileWrapper(open(the_file, 'rb'), chunk_size),
content_type=mimetypes.guess_type(the_file)[0])
response['Content-Length'] = os.path.getsize(the_file)
response['Content-Disposition'] = "attachment; filename=%s" % filename
return response
Django download a file
You missed underscore in argument document_root. But it's bad idea to use serve
in production. Use something like this instead:
import os
from django.conf import settings
from django.http import HttpResponse, Http404
def download(request, path):
file_path = os.path.join(settings.MEDIA_ROOT, path)
if os.path.exists(file_path):
with open(file_path, 'rb') as fh:
response = HttpResponse(fh.read(), content_type="application/vnd.ms-excel")
response['Content-Disposition'] = 'inline; filename=' + os.path.basename(file_path)
return response
raise Http404
Django: Cannot download generating file
Because in your case f.read()
is returning an empty string, you have to manually move the file pointer at the beginning of the file in order to read the content after writing
def report_generate(request):
f = open("test.txt", "w+")
for i in range(10):
f.write("This is line %d\r\n" % (i + 1))
f.seek(0) # Move the pointer at the beginning
response = HttpResponse(f.read(), content_type='text/plain')
f.close() # Close the file
filename = "guru99.txt"
response['Content-Disposition'] = 'attachment; filename="%s"' % filename
return response
Related Topics
Comparing Two .Txt Files Using Difflib in Python
Python Pandas: Group Datetime Column into Hour and Minute Aggregations
Matplotlib: Plotting Numerous Disconnected Line Segments with Different Colors
How to Crop an Image with Pygame
Optimizing Database Queries in Django Rest Framework
Sort a Pandas Dataframe Series by Month Name
How to Make Built-In Containers (Sets, Dicts, Lists) Thread Safe
How to Tell Distutils to Use Gcc
Tensorflow: How to Replace or Modify Gradient
Get Last Result in Interactive Python Shell
Return a Download and Rendered Page in One Flask Response
How to Read File with Space Separated Values in Pandas
Sql-Like Window Functions in Pandas: Row Numbering in Python Pandas Dataframe
How to Create Downloading Progress Bar in Ttk
Group Duplicate Column Ids in Pandas Dataframe
Replace Column Values in One Dataframe by Values of Another Dataframe