I'm trying to download a file via an url. It is normally downloaded, but the problem is that , when I'm trying to open the file, it has 0 bytes.
Does anyone met this problem, or have idea from where can it come?
This is my code
def download():
file_name = "/opt/static/avatar/20/mouse.png"
response = HttpResponse(content_type='application/force-download')
response['Content-Disposition'] = 'attachment; filename=%s' % smart_str(file_name)
response['X-Sendfile'] = smart_str(path)
return response
NginX does not support X-Sendfile header. You must use X-Accel-Redirect instead:
response['X-Accel-Redirect'] = smart_str(path)
Related
I have a view like this:
def download(request):
response = StreamingHttpResponse([save_virtual_workbook(make_xl_workbook())], content_type="application/vnd.ms-excel")
response[u'Content-Disposition'] = u'attachment; filename="%s"' % filename
return response
But it waits to prompt the user to download until after make_xl_workbook has run.
I was reading that I can't chunk out the data returned from make_xl_workbook because xlsx files are zipped. So I was hoping to start the download right away, then run the function and then pump the full data into the response once that function has run.
I also tried this but it didn't seem to help. It still runs the full function make_xl_workbook before the download starts.
def download(request):
def save_xl():
yield save_virtual_workbook(make_xl_workbook())
response = StreamingHttpResponse(save_xl(), content_type="application/vnd.ms-excel")
response[u'Content-Disposition'] = u'attachment; filename="%s"' % filename
return response
Update: Also tried this and got the same behavior, no change.
def download(request):
def save_xl():
yield ''
yield save_virtual_workbook(make_xl_workbook())
response = StreamingHttpResponse(save_xl(), content_type="application/vnd.ms-excel")
response[u'Content-Disposition'] = u'attachment; filename="%s"' % filename
return response
I have a Pandas dataframe in my Flask app that I want to return as a CSV file.
return Response(df.to_csv())
The problem is that the output appears in the browser instead of downloading as a separate file. How can I change that?
I tried the following as well but it just gave empty output.
response = make_response(df.to_csv())
response.headers['Content-Type'] = 'text/csv'
return Response(response)
Set the Content-Disposition to tell the browser to download the file instead of showing its content on the page.
resp = make_response(df.to_csv())
resp.headers["Content-Disposition"] = "attachment; filename=export.csv"
resp.headers["Content-Type"] = "text/csv"
return resp
This is pretty much the same solution but you can just pass the same info into Response:
return Response(
df.to_csv(),
mimetype="text/csv",
headers={"Content-disposition":
"attachment; filename=filename.csv"})
set the content-disposition and use stringIO to convert dataframe to stream, below is the code to achieve,
execel_file = StringIO.StringIO()
filename = "%s.csv" % ('output file')
df.to_csv(execel_file, encoding='utf-8')
csv_output = execel_file.getvalue()
execel_file.close()
resp = make_response(csv_output)
resp.headers["Content-Disposition"] = ("attachment; filename=%s" % filename)
resp.headers["Content-Type"] = "text/csv"
return resp
I always used to save the files I wanted to make downloadable in django. In my project I used that code for example:
def keyDownload(request, benutzername):
benutzernameKey = benutzername +".key"
fsock = open('/var/www/openvpn/examples/easy-rsa/2.0/keys/'+benutzernameKey, 'r')
response = HttpResponse(fsock, mimetype='application/pgp-keys')
response['Content-Disposition'] = "attachment; filename = %s " % (benutzernameKey)
return response
I got a pdf file which I get through urllib:
url = "http://www.urltomypdf.com"
sock = urllib2.urlopen(url)
with open('report.pdf', 'wb') as f:
while True:
content = sock.read()
if not content: break
f.write(content)
At the moment I am saving the pdf in a file called report.pdf. But my aim is to render it directly to my template with a function in django. Is that possible ?
With the introduction of Django 1.5, the StreamingHttpResponse class has been made available to stream a response based on an iterator. Your view and iterator could look like this:
def stream_pdf(url, chunk_size=8192):
sock = urllib2.urlopen(url)
while True:
content = sock.read(chunk_size)
if not content: break
yield content
def external_pdf_view(request, *args, **kwargs):
url = <url> # specify the url here
response = StreamingHttpResponse(stream_pdf(url), content_type="application/pdf")
response['Content-Disposition'] = "filename='%s'" % <filename> #specify the filename here
return response
Pre Django 1.5, it is still possible to stream a response by passing an iterator to HttpResponse, but there are several caveats. First, you need to use the #condition(etag_func=None) decorator on your view function. Secondly, some middleware can prevent a properly streamed response, so you'll need to bypass that middleware. And finally, a chunk of content only gets send when it reaches a length of 1024 bytes, so chunk_size should be over 1024.
I need to associate a link such as "Protocol" and then drive to download a PDF file. Is giving 404 error in mapping the url and would like some help regarding view.
url-Protocol:
urlpatterns += patterns('suap.views',(r'^manuais/$', 'manuais'),
(r'^static/manuais/manual_protocolo.pdf$', 'manual_pdf'))
view-Protocol:
def manual_pdf(request):
response = HttpResponse(extension='.pdf')
response['Content-Disposition'] = 'attachment; filename="manual_protocolo.pdf"' %manual_protocolo
return response
you have to use mod x_sendfile in your server. see
also make a small modification to the code
response = HttpResponse(mimetype='application/pdf')
response['Content-Disposition'] = 'attachment; filename=%s' % smart_str('manual_protocolo.pdf')
response['X-Sendfile'] = "/path/to/manual_protocolo.pdf"
return response
I have a download link on one of my webpage in django.
When i download a audio file of 75mb it downloads but nothing in the audio, its 0bytes.
this is my code:
from django.core.servers.basehttp import FileWrapper
import mimetypes
rec_file = settings.WEB_PATH + "/media/recording/" + filename
wrapper = FileWrapper( open(rec_file, "r"))
contentType = mimetypes.guess_type(rec_file)[0]
response = HttpResponse(wrapper, mimetype = "application/force-download")
response['Content-Length'] = os.path.getsize(rec_file)
response['Content-Disposition'] = "attachment; filename=" + filename
return response
i use apache server. can anyone tell me the solution ?
Couldn't say what's wrong with your code, but you shouldn't be doing that anyways. You should serve static files directly from Apache or use X-Sendfile.