I'm a student of engineering and I'm supposed to create a little app for a project using python-flask, but at the moment I'm stuck at the construction of the Upload system: I've just copied the code provided by the professor but it doesn't work, it says "Errno30, read-only file system /static". I couldn't find a way to solve it so need help.
Pasting here the view function:
#app.route("/upload", methods=["POST", "GET"])
def upload_page():
folder_name = str(session.get('park'))
park=Parks.query.filter_by(id_park=folder_name).first()
if not os.path.exists('/static/Uploads/' + str(folder_name)):
os.makedirs('/static/Uploads/' + str(folder_name))
file_url = os.listdir('/static/Uploads/' + str(folder_name))
file_url = [str(folder_name) + "/" + file for file in file_url]
formupload = UploadForm()
print folder_name
if formupload.validate_on_submit():
filename = photos.save(formupload.file.data,
name=folder_name + '.jpg', folder=folder_name)
file_url.append(filename)
park.image = file_url
db.session.commit()
return redirect(url_for("home_page"))
return render_template("upload.html", formupload=formupload, filelist=file_url)
I'm not sure at all of whatever is written here, but I have to say that "Uploads" is a folder that I've created just now for this, and it is inside the folder "static".
I paste even the error page:
OSError
OSError: [Errno 30] Read-only file system: '/static'
Traceback (most recent call last)
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site- packages/flask/app.py", line 2464, in __call__
return self.wsgi_app(environ, start_response)
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site- packages/flask/app.py", line 2450, in wsgi_app
response = self.handle_exception(e)
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site- packages/flask/app.py", line 1867, in handle_exception
reraise(exc_type, exc_value, tb)
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site- packages/flask/app.py", line 2447, in wsgi_app
response = self.full_dispatch_request()
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site- packages/flask/app.py", line 1952, in full_dispatch_request
rv = self.handle_user_exception(e)
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site- packages/flask/app.py", line 1821, in handle_user_exception
reraise(exc_type, exc_value, tb)
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site- packages/flask/app.py", line 1950, in full_dispatch_request
rv = self.dispatch_request()
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site- packages/flask/app.py", line 1936, in dispatch_request
return self.view_functions[rule.endpoint](**req.view_args)
File "/Users/riccardo/PycharmProjects/flaskProject/app.py", line 130, in upload_page
os.makedirs('/static/Uploads/' + str(folder_name))
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/os.py", line 150, in makedirs
makedirs(head, mode)
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/os.py", line 150, in makedirs
makedirs(head, mode)
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/os.py", line 157, in makedirs
mkdir(name, mode)
OSError: [Errno 30] Read-only file system: '/static'
The error message is pretty self-explaining.
Your code tries to write to /static/Uploads which you are not allowed to write to. Probably for a good reason, as /static/Uploads is an absolute URL and very high up in the file system.
You probably want to write into either the app's directory or into another folder in the app's user directory.
You could remove the leading slash of the path to make it a relative URL.
#app.route("/upload", methods=["POST", "GET"])
def upload_page():
folder_name = str(session.get('park'))
park=Parks.query.filter_by(id_park=folder_name).first()
if not os.path.exists('static/Uploads/' + str(folder_name)):
os.makedirs('static/Uploads/' + str(folder_name))
file_url = os.listdir('/static/Uploads/' + str(folder_name))
Also please note that Flask-Uploads is obsolete - you should use https://github.com/jugmac00/flask-reuploaded
Also, you use Python 2.7, which is no longer maintained. You should use Python 3.10.
Related
I am using flask to handle image uploads and whenever I upload a jpg, jpeg, or png the program I made is able to handle the upload. However, whenever uploading a .jfif image the program returns the error flask_uploads.UploadNotAllowed. Thanks for any help in advance!
The code the program is having an issue with is:
file_name = photos.save(request.files['photo'])
full traceback:
Traceback (most recent call last):
File
"C:\Users\user\AppData\Local\Programs\Python\Python36\lib\site-packages\flask\app.py", line 2464, in __call__
return self.wsgi_app(environ, start_response)
File "C:\Users\user\AppData\Local\Programs\Python\Python36\lib\site-packages\flask\app.py", line 2450, in wsgi_app
response = self.handle_exception(e)
File "C:\Users\user\AppData\Local\Programs\Python\Python36\lib\site-packages\flask\app.py", line 1867, in handle_exception
reraise(exc_type, exc_value, tb)
File "C:\Users\user\AppData\Local\Programs\Python\Python36\lib\site-packages\flask\_compat.py", line 39, in reraise
raise value
File "C:\Users\user\AppData\Local\Programs\Python\Python36\lib\site-packages\flask\app.py", line 2447, in wsgi_app
response = self.full_dispatch_request()
File "C:\Users\user\AppData\Local\Programs\Python\Python36\lib\site-packages\flask\app.py", line 1952, in full_dispatch_request
rv = self.handle_user_exception(e)
File "C:\Users\user\AppData\Local\Programs\Python\Python36\lib\site-packages\flask\app.py", line 1821, in handle_user_exception
reraise(exc_type, exc_value, tb)
File "C:\Users\user\AppData\Local\Programs\Python\Python36\lib\site-packages\flask\_compat.py", line 39, in reraise
raise value
File "C:\Users\user\AppData\Local\Programs\Python\Python36\lib\site-packages\flask\app.py", line 1950, in full_dispatch_request
rv = self.dispatch_request()
File "C:\Users\user\AppData\Local\Programs\Python\Python36\lib\site-packages\flask\app.py", line 1936, in dispatch_request
return self.view_functions[rule.endpoint](**req.view_args)
File "c:\Users\user\Desktop\OCR - Copy\OCRWebsite\app.py", line 421, in upload
file_name = photos.save(request.files['photo'])
File "C:\Users\user\AppData\Local\Programs\Python\Python36\lib\site-packages\flask_uploads.py", line 416, in save
raise UploadNotAllowed()
flask_uploads.UploadNotAllowed
You are probably using the standard IMAGES set:
https://github.com/jugmac00/flask-reuploaded/blob/f05077b085393dbc607c01b8daff1b3a8b2dbf0b/src/flask_uploads/extensions.py#L29
This set does not allow .jfif files.
However, such a set is really only a Python set, so you can create and use your own, or just update the existing one.
IMAGES.update(".jfif")
I am getting this wired error on flask when I want to save a file received on a post request. I tried debugging but I do not understand the error because I use flask save, and on google and other stack overflow questions I found that this has to to with python file API like missing open or wrong flags, but I do not have any flags, or do not need to open any file here.
How I sent the file:
const uploadFile = async (file) =>{
const formData = new FormData();
formData.append("file", file);
fetch("http://localhost:5000/files/upload", {method: "POST", body: formData});
}
How I recive the file:
#app.route('/files/upload', methods = ['POST'])
def recive_upload_file():
file = request.files['file']
filename = file.filename
root_dir = os.path.dirname(os.getcwd())
file.save((os.path.join(root_dir,'backend', 'upload'), filename))
return "done"
As far as I can tell the file is sending correctly because if I try to print the filename in the recive_uploaded_file function I get the correct name.
The Error:
Traceback (most recent call last):
File "c:\Python37\lib\site-packages\flask\app.py", line 2447, in wsgi_app
response = self.full_dispatch_request()
File "c:\Python37\lib\site-packages\flask\app.py", line 1952, in full_dispatch_request
rv = self.handle_user_exception(e)
File "c:\Python37\lib\site-packages\flask_cors\extension.py", line 161, in wrapped_function
return cors_after_request(app.make_response(f(*args, **kwargs)))
File "c:\Python37\lib\site-packages\flask\app.py", line 1821, in handle_user_exception
reraise(exc_type, exc_value, tb)
File "c:\Python37\lib\site-packages\flask\_compat.py", line 39, in reraise
raise value
File "c:\Python37\lib\site-packages\flask\app.py", line 1950, in full_dispatch_request
rv = self.dispatch_request()
File "c:\Python37\lib\site-packages\flask\app.py", line 1936, in dispatch_request
return self.view_functions[rule.endpoint](**req.view_args)
File "index.py", line 239, in upload_file
file.save((os.path.join(root_dir,'backend', 'upload'), filename))
File "c:\Python37\lib\site-packages\werkzeug\datastructures.py", line 3070, in save
copyfileobj(self.stream, dst, buffer_size)
File "c:\Python37\lib\shutil.py", line 82, in copyfileobj
fdst.write(buf)
AttributeError: 'tuple' object has no attribute 'write'
The file path you specified is incorrect. You're trying to write to a tuple as file path:
>>> root_dir = '/root/'
>>> filename = 'test.png'
>>> (os.path.join(root_dir,'backend', 'upload'), filename)
('/root/backend/upload', 'test.png')
You should move the filename inside the os.path.join call.
>>> os.path.join(root_dir,'backend', 'upload', filename)
'/root/backend/upload/test.png'
I found the issue.
I had the wrong path, the filename should be inside os.path.join()
file.save((os.path.join(root_dir,'backend', 'upload', filename)))
I'm setting up a flask application to run a machine learning model with a user interface.
I'm running python3 on sublime text (windows).
I'm unable to save files to the directory without it throwing up an error, PermissionDenied Errno13
My folder Web_Demo contains static, templates and main as is standard in Flask.
I've tried using the absolute path names but still had the same errors.
app.config["UPLOAD_FOLDER"]= 'D:/Web_Demo/static/'
#app.route('/analysis.html',methods=['GET', 'POST'])
def analysis():
if request.method == "POST":
if request.files:
file=request.files["data"]
filename=secure_filename(file.filename)
file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))
return redirect(request.url)
return render_template('/analysis.html')
I receive this error as soon as I press the button for upload. This is prior to me choosing and uploading the file itself.
PermissionError: [Errno 13] Permission denied: 'D:/Web_Demo/static/'
I believe I do not have the permissions to write to this folder. If so how do I accomplish this? I have read about solutions involving sudo 775 but could not implement or make sense of it.
Any help would be appreciated.
The entire traceback is as follows:
File "C:\Users\Utsav Dutta\Anaconda3\lib\site-packages\flask\app.py", line 2309, in __call__
return self.wsgi_app(environ, start_response)
File "C:\Users\Utsav Dutta\Anaconda3\lib\site-packages\flask\app.py", line 2295, in wsgi_app
response = self.handle_exception(e)
File "C:\Users\Utsav Dutta\Anaconda3\lib\site-packages\flask\app.py", line 1741, in handle_exception
reraise(exc_type, exc_value, tb)
File "C:\Users\Utsav Dutta\Anaconda3\lib\site-packages\flask\_compat.py", line 35, in reraise
raise value
File "C:\Users\Utsav Dutta\Anaconda3\lib\site-packages\flask\app.py", line 2292, in wsgi_app
response = self.full_dispatch_request()
File "C:\Users\Utsav Dutta\Anaconda3\lib\site-packages\flask\app.py", line 1815, in full_dispatch_request
rv = self.handle_user_exception(e)
File "C:\Users\Utsav Dutta\Anaconda3\lib\site-packages\flask\app.py", line 1718, in handle_user_exception
reraise(exc_type, exc_value, tb)
File "C:\Users\Utsav Dutta\Anaconda3\lib\site-packages\flask\_compat.py", line 35, in reraise
raise value
File "C:\Users\Utsav Dutta\Anaconda3\lib\site-packages\flask\app.py", line 1813, in full_dispatch_request
rv = self.dispatch_request()
File "C:\Users\Utsav Dutta\Anaconda3\lib\site-packages\flask\app.py", line 1799, in dispatch_request
return self.view_functions[rule.endpoint](**req.view_args)
File "D:\Web_Demo\main.py", line 34, in analysis
file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))
File "C:\Users\Utsav Dutta\AppData\Roaming\Python\Python37\site-packages\werkzeug\datastructures.py", line 2799, in save
dst = open(dst, "wb")
PermissionError: [Errno 13] Permission denied: 'D:/Web_Demo/static/'
Try app.config["UPLOAD_FOLDER"]= './static' without the / at the end, normaly this should work.
I use pdfkit to create an invoice pdf. At the moment I just want to save it. Later I will save the invoice filename in the DB and store in on AWS3.
But for now I get an IO Error when trying to save the file, probably because I request it the wrong way:
pdfkit.from_file(render_template('invoice_template.html', invoice_id=1, invioce_date_start=str(date.today()),
invioce_date_end=str(date.today()), invioce_company_name=form.zahlung_firma.data, invioce_user_vorename=form.vorname.data,
invioce_user_surname=form.nachname.data, invioce_user_email=current_user.email), str(current_user.id) + '-invoice.pdf')
The Error:
Traceback (most recent call last):
File "C:\Python27\lib\site-packages\flask\app.py", line 1988, in wsgi_app
response = self.full_dispatch_request()
File "C:\Python27\lib\site-packages\flask\app.py", line 1641, in full_dispatch_request
rv = self.handle_user_exception(e)
File "C:\Python27\lib\site-packages\flask\app.py", line 1544, in handle_user_exception
reraise(exc_type, exc_value, tb)
File "C:\Python27\lib\site-packages\flask\app.py", line 1639, in full_dispatch_request
rv = self.dispatch_request()
File "C:\Python27\lib\site-packages\flask\app.py", line 1625, in dispatch_request
return self.view_functions[rule.endpoint](**req.view_args)
File "C:\Python27\lib\site-packages\flask_login.py", line 758, in decorated_view
return func(*args, **kwargs)
File "C:\Users\User\Eclipse-Workspace\Monteurzimmer\main.py", line 114, in decorated_function
return func(*args, **kwargs)
File "C:\Users\User\Eclipse-Workspace\Monteurzimmer\main.py", line 1252, in logged_in
invioce_user_surname=form.nachname.data, invioce_user_email=current_user.email), str(current_user.id) + '-invoice.pdf')
File "C:\Python27\lib\site-packages\pdfkit\api.py", line 47, in from_file
configuration=configuration, cover_first=cover_first)
File "C:\Python27\lib\site-packages\pdfkit\pdfkit.py", line 41, in __init__
self.source = Source(url_or_file, type_)
File "C:\Python27\lib\site-packages\pdfkit\source.py", line 12, in __init__
self.checkFiles()
File "C:\Python27\lib\site-packages\pdfkit\source.py", line 32, in checkFiles
raise IOError('No such file: %s' % self.source)
IOError: No such file: <!doctype html>
The template itself can be found here, I just edited the jinja variables:
pdfkit.from_file() expects a file object as its input, but render_template() returns a string. Try pdfkit.from_string() instead.
More information: pypi - pdfkit
I am using flask-dance to authenticate to Google's servers.
Config for flask-dance:
from flask.ext.dance.contrib.google import make_google_blueprint
google_blueprint = make_google_blueprint (
client_id=app.config['GOOGLE']['client_id'],
client_secret=app.config['GOOGLE']['client_secret'],
scope=["profile", "email"],
redirect_to="main.index",
login_url="/",
authorized_url="/authorized",
)
app.register_blueprint(google_blueprint,url_prefix="/login")
However, I am getting Warning: Scope has changed from "profile email" to "". after you go through Google's credential dialog box.
Here's the full trace:
Traceback (most recent call last):
File "/home/xxx/.virtualenvs/flask/lib/python2.7/site-packages/flask/app.py", line 1836, in __call__
return self.wsgi_app(environ, start_response)
File "/home/xxx/.virtualenvs/flask/lib/python2.7/site-packages/flask/app.py", line 1820, in wsgi_app
response = self.make_response(self.handle_exception(e))
File "/home/xxx/.virtualenvs/flask/lib/python2.7/site-packages/flask/app.py", line 1403, in handle_exception
reraise(exc_type, exc_value, tb)
File "/home/xxx/.virtualenvs/flask/lib/python2.7/site-packages/flask/app.py", line 1817, in wsgi_app
response = self.full_dispatch_request()
File "/home/xxx/.virtualenvs/flask/lib/python2.7/site-packages/flask/app.py", line 1477, in full_dispatch_request
rv = self.handle_user_exception(e)
File "/home/xxx/.virtualenvs/flask/lib/python2.7/site-packages/flask/app.py", line 1381, in handle_user_exception
reraise(exc_type, exc_value, tb)
File "/home/xxx/.virtualenvs/flask/lib/python2.7/site-packages/flask/app.py", line 1475, in full_dispatch_request
rv = self.dispatch_request()
File "/home/xxx/.virtualenvs/flask/lib/python2.7/site-packages/flask/app.py", line 1461, in dispatch_request
return self.view_functions[rule.endpoint](**req.view_args)
File "/home/xxx/.virtualenvs/flask/lib/python2.7/site-packages/flask_dance/consumer/oauth2.py", line 168, in authorized
client_secret=self.client_secret,
File "/home/xxx/.virtualenvs/flask/lib/python2.7/site-packages/requests_oauthlib/oauth2_session.py", line 199, in fetch_token
self._client.parse_request_body_response(r.text, scope=self.scope)
File "/home/xxx/.virtualenvs/flask/lib/python2.7/site-packages/oauthlib/oauth2/rfc6749/clients/base.py", line 409, in parse_request_body_response
self.token = parse_token_response(body, scope=scope)
File "/home/xxx/.virtualenvs/flask/lib/python2.7/site-packages/oauthlib/oauth2/rfc6749/parameters.py", line 376, in parse_token_response
validate_token_parameters(params)
File "/home/xxx/.virtualenvs/flask/lib/python2.7/site-packages/oauthlib/oauth2/rfc6749/parameters.py", line 406, in validate_token_parameters
raise w
Warning: Scope has changed from "profile email" to "".
On the Chrome Dev Console I get this (after the Account Chooser window right before the traceback):
GET http://localhost:5000/login/authorized?state=11rtXcAHJm0jloiDpM8IrazD9uLT3b…xnXM0ZB1DumOPqFOgu-x19CDSbDfQoKLWVEfBRTQIg.gvDk1rm330AV3oEBd8DOtNAR0Vr7lQI 500 (INTERNAL SERVER ERROR)
Navigated to http://localhost:5000/login/authorized?state=11rtXcAHJm0jloiDpM8IrazD9uLT3b…xnXM0ZB1DumOPqFOgu-x19CDSbDfQoKLWVEfBRTQIg.gvDk1rm330AV3oEBd8DOtNAR0Vr7lQI
If I do os.environ['OAUTHLIB_RELAX_TOKEN_SCOPE'] = '1' it works, but I don't think this is a solution but more of a workaround for now. :(
I opened a ticket on the issue Google OAuth2 returns no scope on authentication breaks scope test #306 on the issue.
From what I can tell from https://www.rfc-editor.org/rfc/rfc6749#section-3.3, Google isn't required to return the scope (unless the scope was changed), am I reading this correctly?
Nearest thing I can figure is there is a bug in the oauthlib plugin which I opened a bug report with already.
From the bug report, you can fix the issue by changing the file /oauth2/rfc6749/tokens.py in the plugin on Line 30 from self._new_scope = set(utils.scope_to_list(params.get('scope', ''))) to self._new_scope = set(utils.scope_to_list(params.get('scope', old_scope)))
Fix was merged: https://github.com/idan/oauthlib/pull/323