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')
Related
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'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
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 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)