flask resfull app permission error on file save - python

I'm trying to upload a file to my REST API, and then save it in a directory.
It's running on the build in flask development server.
I get this error:
PermissionError: [Errno 13] Permission denied: 'uploads/'
Here is my code:
class Upload(Resource):
def post(self):
new_file = request.files['file']
new_file.save('uploads/', 'file_name')
I understand why I get this error, but I can't figure out how to change permissions. How is that done?
I'm on windows 7.
BR Kresten

Did you set app['UPLOAD_FOLDER'] = 'uploads'?
Here is what I thought better for your uploaded files:
home_dir = os.path.expanduser("~")
UPLOAD_FOLDER = os.path.join(home_dir, "upload")
app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER
class Upload(Resource):
def post(self):
new_file = request.files['file']
file_name = secure_filename(new_file.filename)
new_file.save(os.path.join(app.config['UPLOAD_FOLDER'], file_name))

Related

Get file url in flask api

I have an API to upload files in my flask application. It's uploading the file perfectly fine but when I try to get the file using the path of url which I got from my api, I am getting 404 file not found.
Here is my code.
app = Flask(__name__)
app.config['UPLOAD_FOLDER'] = 'uploads'
def generate_unique_filename(filename):
_, ext = os.path.splitext(filename)
unique_filename = f"{uuid.uuid4().hex}{ext}"
path = os.path.join(app.config['UPLOAD_FOLDER'], unique_filename)
return unique_filename, path
#app.route('/upload', methods=['POST'])
def upload_file():
file = request.files['file']
if file:
filename, path = generate_unique_filename(file.filename)
file.save(path)
file_url = f"{request.host_url}{app.config['UPLOAD_FOLDER']}/{filename}"
return jsonify({'file_url': file_url}), 201
else:
return jsonify({'error': 'No file was uploaded.'}), 400
I want to get url of my uploaded file from my api that can be opened.

PIL.UnidentifiedImageError PIL.UnidentifiedImageError: cannot identify image file 'd:\\a/images/.pdf'

from PIL import Image
import PyPDF2
tess.pytesseract.tesseract_cmd = r'C:\Users\szaid\AppData\Local\Programs\Tesseract-OCR\tesseract'
translator=Translator()
project_dir = os.path.dirname(os.path.abspath(__file__))
app = Flask(__name__,
static_url_path='',
static_folder='static',
template_folder='template')
photos = UploadSet('photos', IMAGES)
pdf = UploadSet('pdf', DOCUMENTS)
app.config['DEBUG'] = True
app.config['UPLOAD_FOLDER']= 'images'
class Get(object):
def __init__(self, file): enter code here
if render_template('image.html'):
self.file = tess.image_to_string(Image.open(project_dir + '/images/'+ file))
elif render_template('pdf.html'):
self.file = PyPDF2.PdfFileReader(project_dir+'/pdff/'+ file)
And below, this is backend code to save the file in 'images' folder but its giving me an error.
I mean there is two different html pages and in both pages, there is an option to upload file and image. but dont know how to manage in flask...
#app.route('/pdf', methods=["GET","POST"])
def pdf():
if request.method == 'POST':
if 'pdf' not in request.files:
return 'there is no photo'
name1 = request.form['pdf-name'] + '.pdf'
pdf = request.files['pdf']
path = os.path.join(app.config['UPLOAD_FOLDER'], name1)
pdf.save(path)
TextObject = Get(name1)
return TextObject.file
return render_template('pdf.html')
error
You're getting this error because your path to the PDF file is wrong. You've added the file extension but the path is missing the file name. You also have a problem with your slashes in the path. A correct path would be like:
"D:\images\yourFileName.pdf"

Django settin up Media files on IIS

I have a Django App which creates PDF files on the server. On the development server it works well but on IIS it doesnt create the file. I have given all the persmission yet theres no luck. I wrote a simple script to write a text file and that too doesnt work on IIS. Any help to resolve this is appriciated.
Thank you.
def fileWriteTest(request):
f = open("media/testwrite.txt", "a")
f.write("Now the file has more content!")
f.close()
print("File Written!")
return HttpResponse("Done !")
FileNotFoundError at /accounts/testfile/
[Errno 2] No such file or directory: 'media/testwrite.txt'
I found a work around.
'''
from django.conf import settings
import os
def fileWriteTest(request):
my_file = os.path.join(settings.MEDIA_ROOT, str("testwrite4.txt"))
f = open(my_file, "a")
f.write("Now the file has more content!")
f.close()
print("File Written!")
return HttpResponse(str(my_file))
'''

Flask upload cannot find directory in server

I have problem with Flask upload in local machine code are working but when upload code to server using apache show error
IOError: [Errno 2] No such file or directory:
u'app/static/avatars/KHUON.S.png'
Code :
ALLOWED_EXTENSIONS = set(['png', 'jpg', 'jpeg', 'gif'])
app.config['UPLOAD_FOLDER'] = 'app/static/avatars'
app.config['MAX_CONTENT_LENGTH'] = 1 * 600 * 600
def allowed_file(filename):
return '.' in filename and filename.rsplit('.', 1)[1] in ALLOWED_EXTENSIONS
#app.route('/User/Profile', methods=['GET', 'POST'])
def upload_profile():
if request.method == 'POST':
file = request.files['file']
if file and allowed_file(file.filename):
filename = secure_filename(file.filename)
file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))
else:
flash("File extension not allow.")
return redirect(url_for('upload_profile', upload='error'))
return render_template("profile.html")
Ok, in upload.py you could do something like
import os
absolute_path = os.path.abspath(UPLOAD_FOLDER+file_name)
os.path.abspath returns the absolute path from the given relative path.

Flask - Errno 13 premission denied

I'm writing a small web page whose task is to let a user upload his input file and with uploading I want to execute my calculation program in python which will give me output for the user.
My code looks like this:
import os
import os.path
import datetime
import subprocess
from flask import Flask, render_template, request, redirect, url_for
from werkzeug import secure_filename
app = Flask(__name__)
app.config['UPLOAD_FOLDER'] = 'uploads'
app.config['ALLOWED_EXTENSIONS'] = set(['txt', 'gro', 'doc', 'docx'])
current_time = datetime.datetime.now()
file_time = current_time.isoformat()
proper_filename = file_time
def allowed_file(filename):
return '.' in filename and \
filename.rsplit('.', 1)[1] in app.config['ALLOWED_EXTENSIONS']
def run_script():
subprocess.call(['/home/martyna/Dropbox/programowanie/project_firefox/topologia.py', '/uploads/proper_filename'])
#app.route('/')
def index():
return render_template('index.html')
#app.route('/upload', methods = ['POST'])
def upload():
file = request.files['file']
if file and allowed_file(file.filename):
file.save(os.path.join(app.config['UPLOAD_FOLDER'], proper_filename))
run_script().start()
return "Thank you for uploading"
if __name__ == '__main__':
app.debug = True
app.run(host='0.0.0.0')
Uploading goes well, but the problem is that when I hit upload I get message OSError: [Errno 13] Permission denied and the line causing the problem is:
subprocess.call(['/home/martyna/Dropbox/programowanie/project_firefox/topologia.py', '/uploads/2014-05-16T22:08:19.522441'])
program topologia.py runs from command python topologia.py input_file
I have no idea how to solve that problem.
You have two problems:
Your script is probably not marked as executable. You can work around that by using the current Python executable path; use sys.executable to get the path to that.
You are telling the script to process /uploads/proper_filename, but the filename you actually upload your file to is not the same at all; you should use the contents of the string referenced by proper_filename instead.
Put these two together:
import sys
from flask import current_app
def run_script():
filename = os.path.join(current_app.config['UPLOAD_FOLDER'], proper_filename)
subprocess.call([
sys.executable,
'/home/martyna/Dropbox/programowanie/project_firefox/topologia.py',
filename])
You do not need to call .start() on the result of run_script(); you'll get an attribute error on NoneType. Just call run_script() and be done with it:
run_script()
Executing a script from a command line and from a server will not be done with the same permissions.
user#mycomputer:~$ ./script
In this exemple, ./script is launched by user. So if it does some inputs/outputs, the access rigths will depend on user rights.
When it is a server that runs the script, in your case Flask, it is probably www-data that launch the script. So the access rights are not the same.
So to create a file into a folder the user executing the script should have the permissions on the folder.

Categories