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
🌐
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'
Discussions

Import Error when importing secure_filename from Werkzeug.utils : Forums : PythonAnywhere
Hello - I am getting this error log on my webapp when I try to import secure_filename from Werkzerug. Can you please point out where I am might be doing this wrong? More on pythonanywhere.com
🌐 pythonanywhere.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
werkzeug - Flask - Do I need to use secure_filename() on uploads to S3/Google Cloud? - Stack Overflow
In the Flask documentation for file uploads, they recommend use of secure_filename() to sanitize a file's name before storing it. Here's their example: uploaded_file = request.files['file'] if More on stackoverflow.com
🌐 stackoverflow.com
Cannot import secure_filename from werkzeug
Python 3.5 with werkzeug 1.0.1 # export FIOWEBVIEWER_SETTINGS=$(pwd)/config.cfg; python create_tables.py Traceback (most recent call last): File "create_tables.py", line 13, in from fioweb... More on github.com
🌐 github.com
0
February 8, 2021
🌐
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
🌐
Lublin
matrix.umcs.lublin.pl › DOC › python-flask-doc › html › patterns › fileuploads.html
Uploading Files — Flask 0.12.1 documentation
import os from flask import Flask, request, redirect, url_for from werkzeug.utils import secure_filename UPLOAD_FOLDER = '/path/to/the/uploads' ALLOWED_EXTENSIONS = set(['txt', 'pdf', 'png', 'jpg', 'jpeg', 'gif']) app = Flask(__name__) app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER
🌐
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 = secure_filename(file.filename) file.save(os.path.joi...
🌐
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 - secure_filename is a function provided by Flask's werkzeug.utils module that is used to sanitize and secure filenames before storing them on the server. This is important for security reasons.
🌐
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.
🌐
Miguel Grinberg
blog.miguelgrinberg.com › post › handling-file-uploads-with-flask
Handling File Uploads With Flask - miguelgrinberg.com
July 8, 2020 - Since February 2020 Flask-Uploads can't be installed from PyPi anymore when Werkzeug 1.0 removed a deprecated way to import secure_filename.
Find elsewhere
🌐
Flask
flask.palletsprojects.com › en › stable › patterns › fileuploads
Uploading Files — Flask Documentation (3.1.x)
import os from flask import Flask, flash, request, redirect, url_for from werkzeug.utils import secure_filename UPLOAD_FOLDER = '/path/to/the/uploads' ALLOWED_EXTENSIONS = {'txt', 'pdf', 'png', 'jpg', 'jpeg', 'gif'} app = Flask(__name__) app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER
🌐
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) file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename)) core.updatelog('File Uploaded.. Filename: ' + filename) # saveas = filename.split('.')[0] anls = analysis.analyze(filename) return (anls) else: return ( 'error: Invalid file format! only .crx files allowed. If you\'re trying to upload zip file rename it to
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'
🌐
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 - 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(): if 'file' not in request.files: return redirect(request.url) file ...
🌐
GitHub
github.com › ovh › fiowebviewer › issues › 4
Cannot import secure_filename from werkzeug · Issue #4 · ovh/fiowebviewer
February 8, 2021 - # export FIOWEBVIEWER_SETTINGS=$(pwd)/config.cfg; python create_tables.py Traceback (most recent call last): File "create_tables.py", line 13, in <module> from fiowebviewer.engine.run import ( File "/opt/fiowebviewer/fiowebviewer/__init__.py", line 5, in <module> from fiowebviewer.engine.run import ( File "/opt/fiowebviewer/fiowebviewer/engine/run.py", line 38, in <module> from fiowebviewer.engine.view import * File "/opt/fiowebviewer/fiowebviewer/engine/view.py", line 21, in <module> from werkzeug import secure_filename ImportError: cannot import name 'secure_filename'
Author   ovh
🌐
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
🌐
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 - Traceback (most recent call last): ... import(module) File "/srv/main.py", line 22, in import storage File "/srv/storage.py", line 23, in from werkzeug import secure_filename ImportError: cannot import name 'secure_filename' from 'werkzeug' (/env/lib/python3.7/site-packages/werkzeu...
Author   GoogleCloudPlatform
🌐
GitHub
github.com › pallets › flask › issues › 1547
Quickstart > File Uploads > incorrect import: secure_filename · Issue #1547 · pallets/flask
August 2, 2015 - It should be imported as: from werkzeug.utils import secure_filename Not: from werkzeug import secure_filename see http://werkzeug.pocoo.org/docs/0.10/utils/
Author   pallets
🌐
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
🌐
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 ...