Unable to download file in django - python

I'm new to django and I have developed a django website which allows people to download epub file by typing the book's name. I have checked the django api about download and the code seems to work fine (no error reported), but there is no download window pops up by my browser. I'm testing on 127.0.0.1:8000 and here is part of my code
view.py
def download(request, file_path, book_name):
if os.path.exists(file_path):
response = HttpResponse(content_type="application/epub+zip")
response['X-Sendfile'] = file_path
response['Content-Disposition'] = 'attachment; filename=abc.epub'
print (response)
return response
raise False
According to my console it could find the file path, and by printing the message it shows
<HttpResponse status_code=200, "application/epub+zip">
[26/Mar/2018 18:31:03] "POST / HTTP/1.1" 200 509
Everything seems to work fine, just the download window does not pop up. Does anyone have any idea where is goes wrong? Thanks!
==========
Supplementary:
To give you a full sight of the view file, download is called by index and thats all:
def index(request):
template = loader.get_template('index.html')
book_name = ''
result = ''
if request.method == "POST": # check if user actually type a book name
book_name = request.POST.get("book_name")
cwd = os.getcwd()
if book_name != '': # search and create are functions from other file which would create an epub file and put it in current directory
result = search.search_ask(book_name)
create.create(book_name)
file_path = os.path.join(cwd, book_name) + '.epub'
download(request, file_path, book_name)
context = {'return_value': book_name,
'result_1': result,
'cwd': cwd}
return HttpResponse(template.render(context, request))

you don't return the response object returned by the download method. most be:
return donwload(request, file_path, book_name)
or
download_response = donwload(request, file_path, book_name)
if download_response:
return download_response
else:
# not found or other return.
in your code always return
return HttpResponse(template.render(context, request))

Related

Flask / Python: #after_this_request is not accessed

I trying to delete a file I've created after it was displayed on the webservice.
However with the current placement of the function, it says 'remove_file(response) is not accessed' and when I run the webservice I get an error when outputting the file, as it apparently already has been deleted.
I don't know what to do anymore, I've tried placing the afer_this_request function right after the upload_file declaration, after the return render template, all of it never works. I'm going crazy, so any help would make my year!
#app.route('/', methods=['POST', 'GET'])
def upload_file():
if request.method == 'POST':
myuuid = uuid.uuid4()
# check if the post request has the file part
if 'file' not in request.files:
return render_template('error.html')
file = request.files['file']
# If the user does not select a file, the browser submits an
# empty file without a filename.
if file.filename == '':
return render_template('error.html')
if file and allowed_file(file.filename):
sfilename = secure_filename(file.filename)
if not os.path.exists(app.config['UPLOAD_FOLDER']):
os.mkdir(app.config['UPLOAD_FOLDER'])
output_path = os.path.join(app.config['UPLOAD_FOLDER'], sfilename)
file.save(output_path)
if 'Alpha Miner' in request.form:
Alpha(pro_file, myuuid)
img_url = url_for('static', filename=str(myuuid) + '.gv.svg')
#after_this_request
def remove_file(response):
os.remove(img_url)
return response
titel = "Petri Net for Alpha Miner: " + sfilename
return render_template('upload.html', img_url=img_url, titel = title)
Try this :
file_handle = open(img_url, 'r')
#after_this_request
def remove_file(response):
try:
os.remove(img_url)
file_handle.close()
except Exception as error:
app.logger.error("Error removing or closing downloaded file handle", error)
return response

Django downloading a file that had been uploaded before

I'm using Django 1.10 and I have a button on my home page that you can click to download a file (PDF or MP4). I have a ajax call going to my views.py
`def downloadfile(request):
if request.POST:
fileviewing = get_object_or_404(FileViewing, pk=request.POST.get("id"))
file_name = fileviewing.file.file.name
file_path = fileviewing.file.file.path
file_wrapper = FileWrapper(file(file_path,'rb'))
file_mimetype = mimetypes.guess_type(file_path)
response = HttpResponse(file_wrapper, content_type=file_mimetype)
response['X-Sendfile'] = file_path
response['Content-Length'] = os.stat(file_path).st_size
response['Content-Disposition'] = 'attachment; filename=%s' % smart_str(file_name)
return response`
This is my function to download a file but nothing happens when it goes through the fuction. There are no errors and the function runs completely but nothing is being downloaded.

Not able to see converted Excel to HTML through Django

I have converted on Excel(with 2 tabs) to HTML. Now I want to display this generated HTML on a webpage with Django code. But I am not able to get the entire data in my webpage.
Following is my Django code.
#api_view(['GET'])
def download_y9cfile1(request, file_name):
filePath = CommonUtils.get_absolute_file_path('app','static','generated','HTML', file_name)
logger.debug("File name is %s" % filePath )
try:
relevantFile = open(filePath,'rb')
response = HttpResponse((relevantFile), content_type='text/html')
response['Content-Disposition'] = 'inline; filename="%s"' %file_name
except IOError:
logger.exception("File doesn't exist")
return HttpResponse("File doesn't exist", status=500)
return response
I think the issue is that Django is not able to read the supporting CSS file for HTML.
Try passing the file contents to HttpResponse instead of the file handle:
response = HttpResponse(relevantFile.read(), content_type='text/html')

Django define name of file to serve

I have wrote a code which let user to download a file. This is the code :
def download_file(request, ref):
filepath = "/home/jedema/code_"+ref+".txt"
filename = os.path.basename(filepath)
final_filename = "code.txt"
return serve(request, filename, os.path.dirname(filepath))
I want to define the file name that user will download. At the moment, the name of downloaded file is the URL after my domain name.
Do you know how to define the name of file downloaded by user ?
You need to set the Content-Dispositionheader in your response. First of all you shouldn't use the serve() view, to deliver the file, because it only works as long as DEBUG = True is set.
With a look at the Django Docs something like the following should do the trick
def download_file(request, ref):
filepath = "/home/jedema/code_"+ref+".txt"
filename = os.path.basename(filepath)
final_filename = "code.txt"
with open(filepath) as f:
response = HttpResponse(f.read(), content_type='text/plain')
response['Content-Disposition'] = 'attachment; filename="%s"' % final_filename
return response
I haven't tested it but it should be a hint into the right direction

Django pdf question with pisa

I want to generate a html template to a pdf file using pisa. I believe I have all the packages I need but I seem to be having problems doing so. Here is my view below so
far what I have done.
EDIT: Here is my latest url, views & template.
url.py
(r'^index/render_pdf/(?P<id>\d+)/$', render_pdf),
views.py
def fetch_resources(uri, rel):
path = os.path.join(settings.MEDIA_ROOT, uri.replace(settings.MEDIA_URL, ""))
return path
def render_pdf (html, id):
invoice_items_list = Invoice_Items.objects.filter(pk=id)
result = StringIO.StringIO()
pdf = pisa.pisaDocument(StringIO.StringIO(html.encode("ISO-8859-1")), dest=result, link_callback=fetch_resources)
return result
In a template, I have this tag.
<a href="{% url c2duo.views.render_pdf invoices.pk %}">
I dont know how much this will help, but this is the function i use to render the pdf:
def fetch_resources(uri, rel):
"""
Callback to allow pisa/reportlab to retrieve Images,Stylesheets, etc.
`uri` is the href attribute from the html link element.
`rel` gives a relative path, but it's not used here.
"""
path = os.path.join(settings.MEDIA_ROOT, uri.replace(settings.MEDIA_URL, ""))
return path
def render_pdf (html):
result = StringIO.StringIO()
pdf = pisa.pisaDocument(StringIO.StringIO(html.encode("ISO-8859-1")), dest=result, link_callback=fetch_resources)
return result
Just for fun, try this instead:
def render_to_pdf(template_src, context_dict):
html = "<html><head><title>Title</title></head><body><h1>Hello</h1></body></html>"
result = StringIO.StringIO()
pdf = pisa.pisaDocument(StringIO.StringIO(html), result)
if not pdf.err:
return http.HttpResponse("" % (repr(result.getvalue())))
else:
raise Exception("The error was %s" % pdf.err)
If you still encounter an error, I'm guessing the error might be in pisa. Are you sure it's up to date?

Categories

Resources