In flask_uploads.py

Change

from werkzeug import secure_filename,FileStorage

to

from werkzeug.utils import secure_filename
from werkzeug.datastructures import  FileStorage
Answer from true man on Stack Overflow
🌐
PythonAnywhere
pythonanywhere.com › forums › topic › 27730
Import Error when importing secure_filename from Werkzeug.utils : Forums : PythonAnywhere
from werkzeug.utils import secure_filename from flask import Flask, redirect, render_template, request, url_for from flask_bootstrap import Bootstrap from .helper import upload_file_to_s3 app = Flask(__name__) Bootstrap(app) app.config["DEBUG"] = True app.config.from_object("mysite.config") comments = [] ALLOWED_EXTENSIONS = {'txt', 'pdf', 'png', 'jpg', 'jpeg', 'gif'} @app.route("/", methods=["GET", "POST"]) def main(): if request.method == "GET": return render_template("main_page.html", comments=comments) comments.append(request.form["contents"]) return redirect(url_for('main')) #https://www.
Discussions

ImportError: cannot import name 'secure_filename' from 'werkzeug'
File "", line , ... name 'secure_filename' from 'werkzeug' (\lib\site-packag es\werkzeug\__init__.py) I think the issue is that adminui is importing from Werkzeug based on the assumption that its Flask dependency will pull in Werkzeug and thus relying on Flask constraining the version of Werkzeug: λ poetry show --tree adminui adminui 0.3.7 Write professional web interface with Python |-- flask ... More on github.com
🌐 github.com
10
September 21, 2020
werkzeug fails to import secure_filename within Docker
Traceback (most recent call last): ... flask_uploads import UploadSet, configure_uploads File "/usr/local/lib/python3.8/site-packages/flask_uploads.py", line 26, in from werkzeug import secure_filename, FileStorage ImportError: cannot import name 'secure_filename' from 'werkzeug' ... More on github.com
🌐 github.com
1
February 9, 2020
Python Flask (deployed on Heroku): ImportError: cannot import name 'secure_filename' from 'werkzeug' when deploying on Heroku - Stack Overflow
When deploying a flask application on heroku im getting the error above. The problem on heroku is that it installs dependencies and Iam not able to overwrite them then, or? On my local server i jus... More on stackoverflow.com
🌐 stackoverflow.com
python - cannot import name 'secure_filename' from 'werkzeug' - Stack Overflow
I'm trying to import secure_filename from werkzeug.utils and it shoot an error. It works fine under my base virtual env. code: # Flask packages from flask import Flask, render_template, request, se... More on stackoverflow.com
🌐 stackoverflow.com
Top answer
1 of 1
7

You are correct.

You only need to use the secure_filename function if you are using the value of request.files['file'].filename to build a filepath destined for your filesystem - for example as an argument to os.path.join.

As you're using a UUID for the filename, the user input value is disregarded anyway.

Even without S3, it would also be safe NOT to use secure_filename if you used a UUID as the filename segment of the filepath on your local filesystem. For example:

uploaded_file = request.files['file']
if uploaded_file:
    file_uuid = uuid.uuid4()
    file.save(os.path.join(app.config['UPLOAD_FOLDER'], file_uuid))
    # Rest of code

In either scenario you'd then store the UUID somewhere in the database. Whether you store the originally provided request.files['file'].filename value alongside that is your choice.

This might make sense if you want the user to see the original name of the file when they uploaded it. In that case it's definitey wise to run the value through secure_filename anyway, so there's never a situation where the frontend displays a listing to a user which includes a file called ../../../../ohdear.txt


the secure_filename docstring also points out some other functionality:

Pass it a filename and it will return a secure version of it. This filename can then safely be stored on a regular file system and passed to :func:os.path.join. The filename returned is an ASCII only string for maximum portability. On windows systems the function also makes sure that the file is not named after one of the special device files.

>>> secure_filename("My cool movie.mov")
'My_cool_movie.mov'
>>> secure_filename("../../../etc/passwd")
'etc_passwd'
>>> secure_filename(u'i contain cool \xfcml\xe4uts.txt')
'i_contain_cool_umlauts.txt'
🌐
Medium
medium.com › @sujathamudadla1213 › what-is-the-use-of-secure-filename-in-flask-9eef4c71503b
What is the use of secure_filename in flask? | by Sujatha Mudadla | Medium
November 25, 2023 - What is the use of secure_filename in flask? from werkzeug.utils import secure_filename @app.route(‘/upload’, methods=[‘GET’, ‘POST’]) def upload_file(): if request.method == …
🌐
ProgramCreek
programcreek.com › python › example › 96284 › werkzeug.utils.secure_filename
Python Examples of werkzeug.utils.secure_filename
def upload_file(): if request.method == 'POST': if 'file' not in request.files: return ('error: No File uploaded') file = request.files['file'] if file.filename == '': return ('error: Empty File!') if file and allowed_file(file.filename): filename = secure_filename(file.filename) ...
🌐
PyPI
pypi.org › project › filenames-secure
filenames-secure · PyPI
Simply $ filenames_secure to obscure and restore.
      » pip install filenames-secure
    
Published   Jan 04, 2021
Version   0.0.8
🌐
GitHub
github.com › bigeyex › python-adminui › issues › 14
ImportError: cannot import name 'secure_filename' from 'werkzeug' · Issue #14 · bigeyex/python-adminui
September 21, 2020 - Meanwhile, the latest version of Werkzeug has moved secure_filename from being importable via werkzeug directly to now only being importable via werkzeug.utils.
Author   bigeyex
🌐
Beautiful Soup
tedboy.github.io › flask › generated › werkzeug.secure_filename.html
werkzeug.secure_filename — Flask API
The filename returned is an ASCII only string for maximum portability. On windows systems the function also makes sure that the file is not named after one of the special device files. >>> secure_filename("My cool movie.mov") 'My_cool_movie.mov' >>> secure_filename("../../../etc/passwd") 'etc_passwd' >>> secure_filename(u'i contain cool \xfcml\xe4uts.txt') 'i_contain_cool_umlauts.txt'
Find elsewhere
🌐
ProgramCreek
programcreek.com › python › example › 60712 › werkzeug.secure_filename
Python Examples of werkzeug.secure_filename
def upload_image(): global secure_filename if flask.request.method == "POST": # 设置request的模式为POST img_file = flask.request.files["image_file"] # 获取需要分类的图片 secure_filename = werkzeug.secure_filename(img_file.filename) # 生成一个没有乱码的文件名 img_path = os.path.join(app.root_path, "predict_img/"+secure_filename) # 获取图片的保存路径 img_file.save(img_path) # 将图片保存在应用的根目录下 print("图片上传成功.") """ """ return flask.redirect(flask.url_for(endpoint="predict")) return "图片上传失败" ... def upload_file(): if
🌐
HackerOne
pullrequest.com › blog › secure-file-uploads-in-flask-filtering-and-validation-techniques
Secure File Uploads in Flask: Filtering and Validation Techniques | HackerOne
March 18, 2024 - Let's start with a basic example of handling file uploads in Flask: from flask import Flask, request, redirect, url_for from werkzeug.utils import secure_filename app = Flask(__name__) @app.route('/upload', methods=['POST']) def upload_file(): ...
🌐
TestDriven.io
testdriven.io › tips › 71b62504-39d7-43ee-8ca2-715a42fc97c7
Tips and Tricks - Flask File Uploads | TestDriven.io
import os from flask import request, current_app from werkzeug.utils import secure_filename @journal_blueprint.route('/upload_file', methods=['POST']) def upload_file(): if 'file' in request.files: file = request.files['file'] filename = ...
🌐
OneUptime
oneuptime.com › home › blog › how to handle file uploads in flask
How to Handle File Uploads in Flask
February 2, 2026 - A production-ready file upload needs to validate the file type, sanitize the filename, and limit the file size. This example adds all three protections. # secure_upload.py # Secure Flask file upload with validation from flask import Flask, request, jsonify from werkzeug.utils import secure_filename import os import uuid app = Flask(__name__) # Configuration UPLOAD_FOLDER = '/var/uploads' MAX_CONTENT_LENGTH = 16 * 1024 * 1024 # 16 MB max file size ALLOWED_EXTENSIONS = {'png', 'jpg', 'jpeg', 'gif', 'pdf', 'doc', 'docx'} app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER app.config['MAX_CONTENT_LENGTH']
🌐
GitHub
github.com › pallets › werkzeug › issues › 1724
werkzeug fails to import secure_filename within Docker · Issue #1724 · pallets/werkzeug
February 9, 2020 - Traceback (most recent call last): File "db_setup.py", line 1, in <module> from app import db File "/usr/src/app/app.py", line 6, in <module> from flask_uploads import UploadSet, configure_uploads File "/usr/local/lib/python3.8/site-packages/flask_uploads.py", line 26, in <module> from werkzeug import secure_filename, FileStorage ImportError: cannot import name 'secure_filename' from 'werkzeug' (/usr/local/lib/python3.8/site-packages/werkzeug/__init__.py)
Author   pallets
🌐
Miguel Grinberg
blog.miguelgrinberg.com › post › handling-file-uploads-with-flask
Handling File Uploads With Flask - miguelgrinberg.com
For those cases Werkzeug provides the secure_filename() function. Let's see how this function works by running a few tests in a Python session: >>> from werkzeug.utils import secure_filename >>> secure_filename('foo.jpg') 'foo.jpg' >>> secure_filename('/some/path/foo.jpg') 'some_path_foo.jpg' >>> secure_filename('../../../.bashrc') 'bashrc'
🌐
Stack Overflow
stackoverflow.com › questions › 70416975 › python-flask-deployed-on-heroku-importerror-cannot-import-name-secure-filen
Python Flask (deployed on Heroku): ImportError: cannot import name 'secure_filename' from 'werkzeug' when deploying on Heroku - Stack Overflow
from werkzeug.utils import secure_filename from werkzeug.datastructures import FileStorage · and this works fine. but when deploying the flask app to heroku, how can I change the the content of flask_uploads.py after it had been installed? python · flask · heroku ·
🌐
GitHub
github.com › GoogleCloudPlatform › getting-started-python › issues › 256
bookshelf error on App Engine: "ImportError: cannot import name 'secure_filename' from 'werkzeug'" · Issue #256 · GoogleCloudPlatform/getting-started-python
February 11, 2020 - bookshelf error on App Engine: "ImportError: cannot import name 'secure_filename' from 'werkzeug'"#256 ... 🚨This issue needs some love.This issue needs some love.triage meI really want to be triaged.I really want to be triaged. ... Traceback (most recent call last): File "/env/lib/python3.7/site-packages/gunicorn/arbiter.py", line 583, in spawn_worker worker.init_process() File "/env/lib/python3.7/site-packages/gunicorn/workers/gthread.py", line 104, in init_process super(ThreadWorker, self).init_process() File "/env/lib/python3.7/site-packages/gunicorn/workers/base.py", line 129, in init_p
Author   GoogleCloudPlatform
🌐
Debug Lab
debuglab.net › home › flask_uploads: importerror: cannot import name ‘secure_filename’
Flask_Uploads: Importerror: Cannot Import Name 'Secure_Filename' - Debug Lab
August 10, 2023 - Python won’t be able to find the requested resource hence throwing an ImportError. ... The problem here lies within Python’s order of execution and structure — it’s simply looking for our specified filename in the wrong area. We’ll have to direct it to the exact module where it resides. ... To address the error issue about Secure_Filename, we make the necessary code corrections.
🌐
Reddit
reddit.com › r › codehunter › comments › r2j4d1 › flask_uploads_importerror_cannot_import_name
r/codehunter - flask_uploads: ImportError: cannot import name 'secure_filename'
Traceback (most recent call last): File "app.py", line 10, in <module> from flask_uploads import UploadSet, configure_uploads, IMAGES File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/flask\_uploads.py", line 26, in <module> from werkzeug import secure_filename, FileStorageImportError: cannot import name 'secure\_filename'
🌐
GitHub
github.com › ultralytics › yolov5 › issues › 13442
ImportError: cannot import name 'secure filename' from 'utils’ (E:(haut_ codelyoL0v5-flask-masterlutils__init__.py · Issue #13442 · ultralytics/yolov5
December 24, 2024 - @serbbda the error suggests that the import of secure_filename is failing because it's not part of YOLOv5's utils module. This function is typically part of Flask (from werkzeug.utils import secure_filename). Verify and replace the import with from werkzeug.utils import secure_filename in your code.
Author   ultralytics