Django Python does not display the correct PDF file - python

I have PDF files which are stored on the server. I am writing a code which prompts users to download the PDF file. I used the following code:
filename ="somepdf.pdf"
filedir = "media/"
filepath = os.path.join( filedir, filename )
pdf=open(filepath)
response = HttpResponse(pdf.read(),content_type='application/pdf')
response['Content-Disposition'] = 'attachment;filename=%s' % filename
return response
For some reason, I rechecked the PDF file that was prompted. The PDF file are not readable (corrupted file perhaps).
Do you know what happen?

You have missed MEDIA_ROOT:
from settings import MEDIA_ROOT
...
filepath = os.path.join(MEDIA_ROOT, filedir, filename)

I found what the answer is.
Apparently the Media_ROOT and Media_URL doesn't work in my case. I use the web browsing debugging tool and locate the discrepancy between the link and the actual PDF.
It should be "/media/" not "media"
I used this code in the HTML to serve the file:
<embed height="100%" width="100%" name="plugin" src="/media/receipts/Receipt_1.pdf" type="application/pdf">

Related

send_from_directory in flask is not downloading images

I followed this tutorial and everything works except for downloading the images that were uploaded. I get 404 errors for everything I try to display in the browser. I can see the images on the hard drive just fine, but they do not download on the /uploads route. ANy ideas?
#bp.route('/uploads/<filename>')
def upload(filename):
print('path: '+str(current_app.config['PRODUCT_UPLOAD_PATH'])+', filename: '+filename)
return send_from_directory(current_app.config['PRODUCT_UPLOAD_PATH'], filename)
Here is the html template that loads the files. The filenames popup proeprly, but the route just shows 404 errors for all the images.
{% for file in files %}
<img src="{{ url_for('main.upload', filename=file) }}" style="width: 64px">
{% endfor %}
config.py to show where the directories are pointing.
MAX_CONTENT_LENGTH = 1024 * 1024
UPLOAD_EXTENSIONS = ['.jpg', '.png', '.gif']
PRODUCT_UPLOAD_PATH = 'uploads/products/'
Here is the solution I found that makes this work. Thanks for the help from everyone!
import os
basedir = os.path.abspath(os.path.dirname(__file__))
class Config(object):
#This string does not work
#PRODUCT_UPLOAD_PATH = 'uploads/products/'
#This is the proper way to configure file paths
PRODUCT_UPLOAD_PATH = os.path.join(basedir, 'uploads', 'products')

Serving files with Flask from dirs outside of static [duplicate]

This question already has answers here:
How to serve static files in Flask
(24 answers)
Closed 5 years ago.
I'm making an upload/download service just for fun but am struggling to serve files that are outside of static directory, which causes an issue because anyone could visit www.mysite.com/static and view the contents.
This is what I have so far. Forgive the ugly paths of my network storage :)
if not os.path.exists('\\ATTILA\\Development\\GIT\\MyCloud\\static\\'+ session['username']):
os.makedirs('\\\\ATTILA\\Development\\GIT\\MyCloud\\static\\'+ session['username'])
#Download links for all files
pathing = []
my_path = '\\\\ATTILA\\Development\\GIT\\MyCloud\\static\\'+ session['username'] + '\\'
os.chdir('\\\\ATTILA\\Development\\GIT\\MyCloud\\static\\'+ session['username'])
for myfile in glob.glob('*'):
downs = my_path + myfile
pathing.append(tuple([downs, myfile]))
In my template I have a simple for loop
{% for myfile, name in pathing %}
<a href='{{ myfile }}' download>{{ name }}</a><br>
{% endfor %}
So my view looks like this:
As it stands my files are downloadable, however if I change the file paths for the downloads to a folder outside of 'static' then instead of download links I get 404 errors that point to the URL + the file path like so www.mysite.com\ATTILLA\Development\some_other_folder any suggestions?
If you want place your app in production you need use solutions like a nginx for serving you static files.
Usually in development stage Flask work with regulary static files (css, js and another) self. It's normal.
If you want hide some private data or uploaded files you need use something like this:
from flask import Flask, make_response
...
#app.route('/file_downloads/<filename>')
def file_downloads(filename):
headers = {"Content-Disposition": "attachment; filename=%s" % filename}
with open('../tmp/you_private_file.zip', 'r') as f:
body = f.read()
return make_response((body, headers))

xhtml2pdf not picking image

i am creating pdf from html and it gets converted but without image. i have tried the absolute urls also but it still doesn't work
pdf function:
def test_pdf(request):
template = get_template('../templates/index.html')
html = template.render(Context(data))
filename = 'pdfs/'+str(random.random())+'.pdf'
file = open(filename, "w+b")
pisaStatus = pisa.CreatePDF(html.encode('utf-8'), dest=file, encoding='utf-8',link_callback=link_callback)
# Return PDF document through a Django HTTP response
file.seek(0)
pdf = file.read()
file.close() # Don't forget to close the file handle
return HttpResponse({"success":"success"})
def link_callback(uri, rel):
sUrl = settings.STATIC_URL # Typically /static/
sRoot = settings.STATIC_ROOT # Typically /home/userX/project_static/
mUrl = settings.MEDIA_URL # Typically /static/media/
mRoot = settings.MEDIA_ROOT # Typically /home/userX/project_static/media/
if uri.startswith(mUrl):
path = os.path.join(mRoot, uri.replace(mUrl, ""))
elif uri.startswith(sUrl):
path = os.path.join(sRoot, uri.replace(sUrl, ""))
else:
return uri # handle absolute uri (ie: http://some.tld/foo.png)
if not os.path.isfile(path):
raise Exception(
'media URI must start with %s or %s' % (sUrl, mUrl)
)
return path
settings file :
PROJECT_ROOT = "/var/www/html/newclone/userapi/"
MEDIA_ROOT = path.join(PROJECT_ROOT,'media')
MEDIA_URL = '/media/'
STATIC_ROOT = path.join(PROJECT_ROOT,'static-root')
STATIC_URL = "/static/"
What is wrong in this. pdf is generated successfully but the images are missing
html file :
<div class="h1"><img src="/media/xyz"></div>
Could not even imagine the error :
in my css i have written :
.main{width:75%;}
because of this images were not visible. I just removed it randomly and images started displaying

Unexpected start downloading while HttpResponse returns two strings

I wrote a code for setting path for import and export files:
def setPath(*args):
abs_path = os.path.dirname(__file__) #/path/to/dir/
root_dir = os.path.split(abs_path)[0] #/path/to/root_of_project/
imp_file_path = "files/links.txt"
exp_file_path = "files/html_data"
abs_imp_file_path = os.path.join(root_dir, imp_file_path) # abs_path to file
abs_exp_file_path = os.path.join(root_dir, exp_file_path)
return HttpResponse(abs_exp_file_path)
It works good, but if I try return both 'abs_imp_file_path' and 'abs_exp_file_path', browser starts to download a file named "download" (without extension) with value of 'abs_exp_file_path' . Why it happens? Please explain where I'm wrong.
HttpResponse just returns a string in your case, that´s why you see this value as download... Normally this should be a fully fledged HTML (document) response.
Please have a look at the django documentation for HttpResponseObjects (https://docs.djangoproject.com/en/1.9/ref/request-response/#httpresponse-objects)

Django - Permission denied to open media in production server (Azure)

Now i am working on production server (AzureWebsites) and i want to open my .txt files.
This is the tree that i used to save my stopwords.txt
-App
-media
-App
stopwords.txt
-static
-templates
settings.py
MEDIA_ROOT = path.join(PROJECT_ROOT, 'media').replace('\\', '/')
# URL that handles the media served from MEDIA_ROOT. Make sure to use a
# trailing slash.
# Examples: "http://media.lawrence.com/media/", "http://example.com/media/"
MEDIA_URL = '/media/'
I want to open the text file using this command
handle = open('/media/stopwords.txt', 'r+')
var = handle.read()
This is the error i got when run my app
[Errno 13] Permission denied: '/media/stopwords.txt'
and when i try to modify the open statements with this
handle = open(settings.MEDIA_ROOT + 'stopwords.txt', 'r+')
i got this error
[Errno 2] No such file or directory: 'D:/home/site/wwwroot/mediastopwords.txt'
Can anyone please help fix this problem?
Try handle = open(settings.MEDIA_ROOT + '/stopwords.txt', 'r+')
According to your tree stopwords is stored under /media/App/stopwords.txt
So to open it you need:
handle = open(settings.MEDIA_ROOT + '/App/stopwords.txt', 'r+')

Categories

Resources