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)))
Related
I am trying to upload and read an excel file but I get a ValueError: negative seek value -45976238, making me believe that the file is corrupted. I think the file got corrupted through the uploading process because I tried creating a brand new excel sheet and uploading it, but I still get the same error. Does anyone know how to resolve or have any idea what the issue is?
Full Error:
raceback (most recent call last):
File "/var/task/flask/app.py", line 2447, in wsgi_app
response = self.full_dispatch_request()
File "/var/task/flask/app.py", line 1952, in full_dispatch_request
rv = self.handle_user_exception(e)
File "/var/task/flask/app.py", line 1821, in handle_user_exception
reraise(exc_type, exc_value, tb)
File "/var/task/flask/_compat.py", line 39, in reraise
raise value
File "/var/task/flask/app.py", line 1950, in full_dispatch_request
rv = self.dispatch_request()
File "/var/task/flask/app.py", line 1936, in dispatch_request
return self.view_functions[rule.endpoint](**req.view_args)
File "/var/task/tech_deploy_ptp_lambda/controllers/zone_assets_controller.py", line 22, in upload
wb = openpyxl.load_workbook(file, data_only=True)
File "/mnt/accesspoint/openpyxl/reader/excel.py", line 315, in load_workbook
reader = ExcelReader(filename, read_only, keep_vba,
File "/mnt/accesspoint/openpyxl/reader/excel.py", line 124, in __init__
self.archive = _validate_archive(fn)
File "/mnt/accesspoint/openpyxl/reader/excel.py", line 96, in _validate_archive
archive = ZipFile(filename, 'r')
File "/var/lang/lib/python3.8/zipfile.py", line 1269, in __init__
self._RealGetContents()
File "/var/lang/lib/python3.8/zipfile.py", line 1354, in _RealGetContents
fp.seek(self.start_dir, 0)
File "/var/lang/lib/python3.8/tempfile.py", line 737, in seek
return self._file.seek(*args)
ValueError: negative seek value -45976238
Angularjs html
<nz-card nzTitle="Upload File" bordered={false} style="flex: 1 1 auto;">
<nz-upload
[nzCustomRequest]="handleUpload"
(nzChange)="handleChange($event)"
>
<p class="ant-upload-drag-icon"><i nz-icon nzType="inbox"></i></p>
<p class="ant-upload-text">
Click or drag CSV/Excel a file to this area to upload
</p>
</nz-upload>
</nz-card>
Angularjs component
handleUpload = (item: any) => {
const formData = new FormData();
formData.append(item.name, item.file);
const headers = new HttpHeaders();
headers.set('Content-Type', 'multipart/form-data');
var upload = this.httpClient.post(this.SERVER_URL, formData,{headers: headers}).subscribe(
(res) => {
console.log("success");
}
}
Flask component
def upload():
file = request.files['file']
wb = openpyxl.load_workbook(file, data_only=True)
print(wb)
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.
So i am making a flask web app and i added a docx to pdf converter but its not working every time i will ran into a problem even though it is simple so i am using this python package to convert docx to pdf https://pypi.org/project/docx2pdf/ and i made it till where i upload files in flask and it start converting. I get error when converting it
this is my code
#app.route("/pdf", methods=["POST"])
def pdf2docx_post():
file = request.files['file']
if file and allowed_file(file.filename):
filename = file.filename
file.save(secure_filename(filename))
convert(filename, filename.split('.')[0] + '.docx')
convert(filename, "output.pdf")
convert(filename)
return send_file("output.pdf", as_attachment=True)
return render_template("pdf.html", wait="Pleas wait your download will start automatically")
i get this error
Traceback (most recent call last):
File "C:\Users\UwU\OneDrive\Desktop\UwU web\Web Development\all-in-one-tools\tools-web\Lib\site-packages\flask\app.py", line 2091, in __call__
return self.wsgi_app(environ, start_response)
File "C:\Users\UwU\OneDrive\Desktop\UwU web\Web Development\all-in-one-tools\tools-web\Lib\site-packages\flask\app.py", line 2076, in wsgi_app
response = self.handle_exception(e)
File "C:\Users\UwU\OneDrive\Desktop\UwU web\Web Development\all-in-one-tools\tools-web\Lib\site-packages\flask\app.py", line 2073, in wsgi_app
response = self.full_dispatch_request()
File "C:\Users\UwU\OneDrive\Desktop\UwU web\Web Development\all-in-one-tools\tools-web\Lib\site-packages\flask\app.py", line 1518, in full_dispatch_request
rv = self.handle_user_exception(e)
File "C:\Users\UwU\OneDrive\Desktop\UwU web\Web Development\all-in-one-tools\tools-web\Lib\site-packages\flask\app.py", line 1516, in full_dispatch_request
rv = self.dispatch_request()
File "C:\Users\UwU\OneDrive\Desktop\UwU web\Web Development\all-in-one-tools\tools-web\Lib\site-packages\flask\app.py", line 1502, in dispatch_request
return self.ensure_sync(self.view_functions[rule.endpoint])(**req.view_args)
File "C:\Users\UwU\OneDrive\Desktop\UwU web\Web Development\all-in-one-tools\app\main.py", line 145, in pdf2docx_post
convert(filename, filename.split('.')[0] + '.docx')
File "C:\Users\UwU\OneDrive\Desktop\UwU web\Web Development\all-in-one-tools\tools-web\Lib\site-packages\docx2pdf\__init__.py", line 102, in convert
paths = resolve_paths(input_path, output_path)
File "C:\Users\UwU\OneDrive\Desktop\UwU web\Web Development\all-in-one-tools\tools-web\Lib\site-packages\docx2pdf\__init__.py", line 94, in resolve_paths
assert str(output_path).endswith(".pdf")
AssertionError
Thanks in advance
NOTE: I ALREADY USED MANY STACKOVERFLOW ANSWERS BUT IT DIDNT WORKED
You can do this..it will work.I struggled with this CoInitialize has not been called error too and it will work in your case too..
from docx2pdf import convert
import os
import pythoncom
convert(your_input_filepath, your_output_directory_path, pythoncom.CoInitialize())
For the your_input_filepath , your_output_directory_path you can give relative input path and output path using os.path.relpath("put_your_filepath_here")
From the error it seems the function expects the filename to end with ".pdf" so you could remove these two extra lines:
convert(filename, filename.split('.')[0] + '.docx')
convert(filename)
and leave
convert(filename, "output.pdf")
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 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