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")
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 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 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.
This question already has answers here:
Flask raises TemplateNotFound error even though template file exists
(14 answers)
Closed 7 years ago.
i use flask and i got this error when i call this url: /login
Here's my login method:
#app.route('/login')
def login():
if authenticateForPanel():
return redirect(url_for("panel"))
else:
getParam = request.args.getlist('redirect_uri')
if getParam:
ref =getParam[0]
else:
ref="/panel"
return render_template( themesDir + g.blogOptions['active_theme']+'/login.html', blogOptions = g.blogOptions, ref=ref )
And the traceback:
Traceback (most recent call last):
File "/Users/ozcan/Library/Python/2.7/lib/python/site-packages/flask/app.py", line 1701, in __call__
return self.wsgi_app(environ, start_response)
File "/Users/ozcan/Library/Python/2.7/lib/python/site-packages/flask/app.py", line 1689, in wsgi_app
response = self.make_response(self.handle_exception(e))
File "/Users/ozcan/Library/Python/2.7/lib/python/site-packages/flask/app.py", line 1687, in wsgi_app
response = self.full_dispatch_request()
File "/Users/ozcan/Library/Python/2.7/lib/python/site-packages/flask/app.py", line 1360, in full_dispatch_request
rv = self.handle_user_exception(e)
File "/Users/ozcan/Library/Python/2.7/lib/python/site-packages/flask/app.py", line 1358, in full_dispatch_request
rv = self.dispatch_request()
File "/Users/ozcan/Library/Python/2.7/lib/python/site-packages/flask/app.py", line 1344, in dispatch_request
return self.view_functions[rule.endpoint](**req.view_args)
File "/Users/ozcan/Documents/python/app.py", line 209, in login
return render_template( themesDir + g.blogOptions['active_theme']+'/login.html', blogOptions = g.blogOptions, ref=ref )
File "/Users/ozcan/Library/Python/2.7/lib/python/site-packages/flask/templating.py", line 124, in render_template
return _render(ctx.app.jinja_env.get_or_select_template(template_name_or_list),
File "/Users/ozcan/Library/Python/2.7/lib/python/site-packages/jinja2/environment.py", line 758, in get_or_select_template
return self.get_template(template_name_or_list, parent, globals)
File "/Users/ozcan/Library/Python/2.7/lib/python/site-packages/jinja2/environment.py", line 719, in get_template
return self._load_template(name, self.make_globals(globals))
File "/Users/ozcan/Library/Python/2.7/lib/python/site-packages/jinja2/environment.py", line 693, in _load_template
template = self.loader.load(self, name, globals)
File "/Users/ozcan/Library/Python/2.7/lib/python/site-packages/jinja2/loaders.py", line 115, in load
source, filename, uptodate = self.get_source(environment, name)
File "/Users/ozcan/Library/Python/2.7/lib/python/site-packages/flask/templating.py", line 61, in get_source
raise TemplateNotFound(template)
TemplateNotFound: static/themes/default/login.html
I am absolutely sure the login.html is there(static/themes/default/404.html).Why can this occur?
You put your template in the wrong place. From the Flask docs:
Flask will look for templates in the templates folder. So if your application is a module, this folder is next to that module, if it’s a package it’s actually inside your package:
See the docs for more information: http://flask.pocoo.org/docs/quickstart/#rendering-templates
I think you shouldn't prepend themesDir. You only pass the filename of the template to flask, it will then look in a folder called templates relative to your python file.