I'm building my first flask app and am having trouble accessing my uploaded files in functions later on in my script. I'm using a variation of the basic Flask Upload script, and currently I have two forms which each take in some sort of text file. I am trying to run the input files through a function later on in my script to compare discrepancies. As it is right now I get this error:
UnboundLocalError: local variable 'filename1' referenced before assignment
I'm trying to get my head around if this is a form issue, or a saved file issue.
Here is my upload folder:
UPLOAD_FOLDER = '/uploads'
ALLOWED_EXTENSIONS = set(['doc', 'docx', 'html', 'txt','rtf'])
app = Flask(__name__)
app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER
app.secret_key = 'MySecretKey'
if not os.path.isdir(UPLOAD_FOLDER):
os.mkdir(UPLOAD_FOLDER)
And here is one of the file uploads, the other is almost identical besides the filenames:
def allowed_audio_file(reference_file):
return '.' in reference_file and \
reference_file.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS
#app.route('/referenceupload', methods=['GET', 'POST'])
def upload_reference_file():
if request.method == 'POST':
# check if the post request has the file part
if 'file' not in request.files:
flash('No file part')
return redirect(request.url)
ref_file = request.files['file']
# if user does not select file, browser also
# submit a empty part without filename
if ref_file.filename == '':
flash('No selected file')
return redirect(request.url)
if ref_file and allowed_audio_file(ref_file.filename):
filename1 = secure_filename(ref_file.filename)
ref_file.save(os.path.join(UPLOAD_FOLDER, filename1))
return redirect(url_for('uploaded_reference_file',
filename1=filename1))
return render_template('reference.html', filename1=filename1)
#app.route('/uploads/<filename1>')
def uploaded_reference_file(filename1):
return send_from_directory(app.config['UPLOAD_FOLDER'],
filename1)
Here is the full error:
File "C:\Python\Python36\lib\site-packages\flask\app.py", line 1997, in __call__
return self.wsgi_app(environ, start_response)
File "C:\Python\Python36\lib\site-packages\flask\app.py", line 1985, in wsgi_app
response = self.handle_exception(e)
File "C:\Python\Python36\lib\site-packages\flask\app.py", line 1540, in handle_exception
reraise(exc_type, exc_value, tb)
File "C:\Python\Python36\lib\site-packages\flask\_compat.py", line 33, in reraise
raise value
File "C:\Python\Python36\lib\site-packages\flask\app.py", line 1982, in wsgi_app
response = self.full_dispatch_request()
File "C:\Python\Python36\lib\site-packages\flask\app.py", line 1614, in full_dispatch_request
rv = self.handle_user_exception(e)
File "C:\Python\Python36\lib\site-packages\flask\app.py", line 1517, in handle_user_exception
reraise(exc_type, exc_value, tb)
File "C:\Python\Python36\lib\site-packages\flask\_compat.py", line 33, in reraise
raise value
File "C:\Python\Python36\lib\site-packages\flask\app.py", line 1612, in full_dispatch_request
rv = self.dispatch_request()
File "C:\Python\Python36\lib\site-packages\flask\app.py", line 1598, in dispatch_request
return self.view_functions[rule.endpoint](**req.view_args)
File "C:\Users\Jesse\eclipse-workspace\WER\src\Word_error_rate\uploads.py", line 55, in upload_reference_file
return render_template('reference.html', filename1=filename1)
UnboundLocalError: local variable 'filename1' referenced before assignment
Related
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.
I am getting the error jinja2.exceptions.TemplateNotFound. Even I have my HTML files in the templates folder, still I am receiving this error. It was working fine sometime ago, and now I am getting this error.
Full error code:
Traceback (most recent call last)
File "E:\price\web\Lib\site-packages\flask\app.py", line 2464, in __call__
return self.wsgi_app(environ, start_response)
File "E:\price\web\Lib\site-packages\flask\app.py", line 2450, in wsgi_app
response = self.handle_exception(e)
File "E:\price\web\Lib\site-packages\flask\app.py", line 1867, in handle_exception
reraise(exc_type, exc_value, tb)
File "E:\price\web\Lib\site-packages\flask\_compat.py", line 39, in reraise
raise value
File "E:\price\web\Lib\site-packages\flask\app.py", line 2447, in wsgi_app
response = self.full_dispatch_request()
File "E:\price\web\Lib\site-packages\flask\app.py", line 1952, in full_dispatch_request
rv = self.handle_user_exception(e)
File "E:\price\web\Lib\site-packages\flask\app.py", line 1821, in handle_user_exception
reraise(exc_type, exc_value, tb)
File "E:\price\web\Lib\site-packages\flask\_compat.py", line 39, in reraise
raise value
File "E:\price\web\Lib\site-packages\flask\app.py", line 1950, in full_dispatch_request
rv = self.dispatch_request()
File "E:\price\web\Lib\site-packages\flask\app.py", line 1936, in dispatch_request
return self.view_functions[rule.endpoint](**req.view_args)
File "E:\price\web\flasktest.py", line 6, in index
return render_template('about.html')
File "E:\price\web\Lib\site-packages\flask\templating.py", line 138, in render_template
ctx.app.jinja_env.get_or_select_template(template_name_or_list),
File "E:\price\web\Lib\site-packages\jinja2\environment.py", line 1068, in get_or_select_template
return self.get_template(template_name_or_list, parent, globals)
File "E:\price\web\Lib\site-packages\jinja2\environment.py", line 997, in get_template
return self._load_template(name, globals)
File "E:\price\web\Lib\site-packages\jinja2\environment.py", line 958, in _load_template
template = self.loader.load(self, name, self.make_globals(globals))
File "E:\price\web\Lib\site-packages\jinja2\loaders.py", line 125, in load
source, filename, uptodate = self.get_source(environment, name)
File "E:\price\web\Lib\site-packages\flask\templating.py", line 60, in get_source
return self._get_source_fast(environment, template)
File "E:\price\web\Lib\site-packages\flask\templating.py", line 89, in _get_source_fast
raise TemplateNotFound(template)
jinja2.exceptions.TemplateNotFound: about.html
Here's my code snippet:
from flask import Flask, render_template
app = Flask('test', template_folder= 'templates')
#app.route('/')
def index():
return render_template('about.html')
if __name__ == '__main__':
app.run(debug = True, host = '127.0.0.1', port = 5000)
Here is the screenshot of my directories:
Update:
My code is working perfectly in a new file. Is it due to cache?
Tried app = Flask(name) but still same issue.
A new Test.py file works completely fine but not the old ones.
have a look at this topic https://flask.palletsprojects.com/en/2.0.x/api/#application-object and head over this section About the First Parameter
so my guess, you should import the right package name,
so try __name__ instead of test
app = Flask(__name__, template_folder='templates')
BTW, Flask already expects templates as default folder to look at, meaning it's optional and you can define your app like so
app = Flask(__name__)
Flask looks for templates by default in the "templates" folder https://flask.palletsprojects.com/en/2.0.x/quickstart/#rendering-templates.
Try this:
app = Flask(__name__)
#app.route('/')
def index():
return render_template('about.html')
Finally I got the solution where it went wrong.
I was doing this:
app = Flask('__name__')
But the correct way was this:
app = Flask(__name__)
I want the user to upload a choosen csv file and send to server - flask where I want to do something with the csv file and send it back as a table for user to get it edited.
I was able to get the uploaded file to flask and activate the python code as a function but as soon as I use the uploaded file in the first line where I have to change the file it gives me back an error : AttributeError: 'SpooledTemporaryFile' object has no attribute 'rename'
I am stuck since I am still pretty new to flask.
Here is the route.py part where the upload file should be edited:
#login_required
def open_file():
'''Opens page with the file that should be edited.'''
if request.method == 'POST':
#check if the post request has the file part
if 'file' not in request.files:
flash('No file part')
return render_template('2_choose_file.html')
file_upload = request.files['file']
#check if the uploaded file a CSV file is
if file_upload and allowed_file(file_upload.filename):
table1 = filter_csv(file_upload)
table2 = table1.to_html(classes='my_class" id = "my_id')
return render_template('3_filtered_file.html', data=table2)
return render_template('2_choose_file.html')
Traceback of the error:
File "C:\Users\aa01725\AppData\Local\Continuum\anaconda3\lib\site-packages\flask\app.py", line 2309, in __call__
return self.wsgi_app(environ, start_response)
File "C:\Users\aa01725\AppData\Local\Continuum\anaconda3\lib\site-packages\flask\app.py", line 2295, in wsgi_app
response = self.handle_exception(e)
File "C:\Users\aa01725\AppData\Local\Continuum\anaconda3\lib\site-packages\flask\app.py", line 1741, in handle_exception
reraise(exc_type, exc_value, tb)
File "C:\Users\aa01725\AppData\Local\Continuum\anaconda3\lib\site-packages\flask\_compat.py", line 35, in reraise
raise value
File "C:\Users\aa01725\AppData\Local\Continuum\anaconda3\lib\site-packages\flask\app.py", line 2292, in wsgi_app
response = self.full_dispatch_request()
File "C:\Users\aa01725\AppData\Local\Continuum\anaconda3\lib\site-packages\flask\app.py", line 1815, in full_dispatch_request
rv = self.handle_user_exception(e)
File "C:\Users\aa01725\AppData\Local\Continuum\anaconda3\lib\site-packages\flask\app.py", line 1718, in handle_user_exception
reraise(exc_type, exc_value, tb)
File "C:\Users\aa01725\AppData\Local\Continuum\anaconda3\lib\site-packages\flask\_compat.py", line 35, in reraise
raise value
File "C:\Users\aa01725\AppData\Local\Continuum\anaconda3\lib\site-packages\flask\app.py", line 1813, in full_dispatch_request
rv = self.dispatch_request()
File "C:\Users\aa01725\AppData\Local\Continuum\anaconda3\lib\site-packages\flask\app.py", line 1799, in dispatch_request
return self.view_functions[rule.endpoint](**req.view_args)
File "C:\Users\aa01725\AppData\Local\Continuum\anaconda3\lib\site-packages\flask_login\utils.py", line 261, in decorated_view
return func(*args, **kwargs)
File "C:\Users\aa01725\newproject\my_app\routes.py", line 83, in open_file
table1 = filter_csv(file_upload)
File "C:\Users\aa01725\newproject\my_app\TEST_filter.py", line 42, in filter_csv
file_in.rename(columns=dict(zip(columns, new_column_names)), inplace=True)
File "C:\Users\aa01725\AppData\Local\Continuum\anaconda3\lib\site-packages\werkzeug\datastructures.py", line 2745, in __getattr__
return getattr(self.stream, name)
AttributeError: 'SpooledTemporaryFile' object has no attribute 'rename'
Part of the python code where it shows the error.
file_in.rename(columns=dict(zip(columns, new_column_names)), inplace=True)
Any help would be great
I found a workaround . Based on this answer . Simply saved the uploaded file to server and using pd.read_csv parse it how I want to and reuse it again.
#app.route('/3_filtered_file', methods=['GET', 'POST'])
#login_required
def open_file():
'''Opens page with the file that was imported from the user.'''
if request.method == 'POST':
#check if the post request has the file part
if 'file' not in request.files:
flash('No file part')
return render_template('2_choose_file.html')
file_upload = request.files['file']
#check if the uploaded file a CSV file is
if file_upload and allowed_file(file_upload.filename):
filename = secure_filename(file_upload.filename)
file_path = os.path.join(app.config['UPLOAD_FOLDER'], filename)
file_upload.save(file_path)
file_to_filter = pd.read_csv(file_path, sep=';', engine='python', encoding='ISO-8859-1')
table1 = filter_csv(file_to_filter)
table2 = table1.to_html(classes='my_class" id = "my_id')
return render_template('3_filtered_file.html', data=table2)
return render_template('2_choose_file.html')
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 followed this tutorial for uploading files to a webserver via Flask, with the notable exception of the return part.
My intention is to upload pictures.
Here's my code:
from flask import Flask, request, jsonify, json, Blueprint, redirect, url_for, send_from_directory
from werkzeug import secure_filename
app = Flask(__name__)
allowed_extensions = set(['png', 'jpg', 'jpeg', 'gif', 'bmp'])
folder_upload = '/Users/myusername/Documents/Project_Upload/'
#CustomersAPI.route('/customers/addpicture', methods=['POST'])
def add_picture():
file = request.files['value']
print file.filename
if file and allowed_file(file.filename):
filename = secure_filename(file.filename)
file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))
#return redirect(url_for('uploaded_file', filename=filename))
return str(url_for('uploaded_file', filename=filename))
return "Unable to upload."
def allowed_file(filename):
return '.' in filename and filename.rsplit('.', 1)[1] in allowed_extensions
if __name__ == '__main__':
app.config['UPLOAD FOLDER'] = folder_upload
app.run(host = '0.0.0.0', debug=True)
As I do not have the HTML files yet (hence the commented out return redirect), I use CocoaRestClient for testing, and here are the parameters I used:
Everything okay so far, until I hit the Submit button. Then, the following error appears:
Traceback (most recent call last):
File "/Library/Python/2.7/site-packages/flask/app.py", line 1836, in __call__
return self.wsgi_app(environ, start_response)
File "/Library/Python/2.7/site-packages/flask/app.py", line 1820, in wsgi_app
response = self.make_response(self.handle_exception(e))
File "/Library/Python/2.7/site-packages/flask/app.py", line 1403, in handle_exception
reraise(exc_type, exc_value, tb)
File "/Library/Python/2.7/site-packages/flask/app.py", line 1817, in wsgi_app
response = self.full_dispatch_request()
File "/Library/Python/2.7/site-packages/flask/app.py", line 1477, in full_dispatch_request
rv = self.handle_user_exception(e)
File "/Library/Python/2.7/site-packages/flask/app.py", line 1381, in handle_user_exception
reraise(exc_type, exc_value, tb)
File "/Library/Python/2.7/site-packages/flask/app.py", line 1475, in full_dispatch_request
rv = self.dispatch_request()
File "/Library/Python/2.7/site-packages/flask/app.py", line 1461, in dispatch_request
return self.view_functions[rule.endpoint](**req.view_args)
File "/Users/myusername/Documents/Project_Omnimoda/API/main.py", line 192, in add_picture
return redirect(url_for('uploaded_file', filename=filename))
File "/Library/Python/2.7/site-packages/flask/helpers.py", line 312, in url_for
return appctx.app.handle_url_build_error(error, endpoint, values)
File "/Library/Python/2.7/site-packages/flask/app.py", line 1641, in handle_url_build_error
reraise(exc_type, exc_value, tb)
File "/Library/Python/2.7/site-packages/flask/helpers.py", line 305, in url_for
force_external=external)
File "/Library/Python/2.7/site-packages/werkzeug/routing.py", line 1649, in build
raise BuildError(endpoint, values, method)
BuildError: ('uploaded_file', MultiDict([('filename', '3611571-dc_holiday.jpg')]), None)
Funny thing is, the image '3611571-dc_holiday.jpg' actually did get copied from my Downloads folder to the Project_Upload folder, so it worked, there's just an error that I'm not sure how to solve.
Any ideas? Thanks.
You haven't defined the uploaded_file endpoint. You need to do that.
#CustomersAPI.route('/customers/SOMETHINGOGESTHERE')
def uploaded_file(filename):
# Do something here with the file, like return it.
return send_from_directory(
folder_upload, filename, as_attachment=True)