Forums

Import Error when importing secure_filename from Werkzeug.utils

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? Thank you!!

2020-06-09 19:19:39,700: Error running WSGI application
2020-06-09 19:19:39,731: ImportError: cannot import name 'secure_filename'
2020-06-09 19:19:39,731:   File "/var/www/virtualta_pythonanywhere_com_wsgi.py", line 16, in <module>
2020-06-09 19:19:39,731:     from flask_app import app as application  # noqa
2020-06-09 19:19:39,731: 
2020-06-09 19:19:39,731:   File "/home/VirtualTA/mysite/flask_app.py", line 6, in <module>
2020-06-09 19:19:39,731:     from werkzeug.utils import secure_filename

The app file is:

    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.zabana.me/notes/flask-tutorial-upload-files-amazon-s3
#app.config.from_object("config")

def allowed_file(filename):
    return '.' in filename and \
           filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS

@app.route("/upload")
def upload():
    return render_template("upload.html")


@app.route("/upload", methods=["POST"])
def upload_file():

    if "user_file" not in request.files:
        return "No user_file key in request.files"

file    = request.files["user_file"]

if file.filename == "":
    return "Please select a file"

if file and allowed_file(file.filename):
    file.filename = secure_filename(file.filename)
    output        = upload_file_to_s3(file, app.config["S3_BUCKET"])
    return str(output)

else:
    return redirect("/")

It looks like your code has been written to work with werkzeug 1.0, but is running with a different version. You can upgrade the version installed for your account easily; as your website is using Python 3.6 and is not using a virtualenv, just run this in bash:

pip3.6 install --user --upgrade werkzeug

...and then reload your website using the button on the "Web" page.

Solution : pip install Flask-Reuploaded

Thanks for sharing, @enzipe2.