Flask 应用程序无法识别动态创建的目录

Flask application not recognising dynamically created directory

我正在尝试创建一个 Flask 应用程序,其中一些功能包括用户能够将图像上传到他们自己的静态文件夹目录中。

我的代码基于 https://github.com/kirsle/flask-multi-upload,事实上它基本上是相同的(除了 AJAX 功能)所以我真的看不出哪里出了问题(我在我自己的环境中使用了 运行 kirsle 的应用程序 - 它工作正常)。

当我访问 /static/uploads/{uuid_goes_here}/img.jpg 时,我可以看到图片 - 显然它正在上传。但是访问 /files/{uuid_goes_here} 会导致 if not os.path.isdir(location) 被执行。

当我注释掉这段代码并尝试直接转到 complete.html 时,{% for file in files %} 似乎没有 运行,因为图像 none 出现了。

我的代码是:

app.py

# Route that will process the file upload
@app.route('/upload', methods=['POST'])
def upload():
    form = request.form
    username = current_user.username #for later when I replace uuid's with usernames
    uuid_key = str(uuid4())
    print("Session Key: {}".format(uuid_key))

    target = "static/uploads/{}".format(uuid_key)
    try:
        os.mkdir(target)
    except FileExistsError:
        return "Couldn't create directory {}".format(target)

    for upload in request.files.getlist("file"):
        filename = upload.filename.rsplit("/")[0]
        destination = '/'.join([target, filename])
        print( "Accepting: {}\n and saving to: {}".format(filename, destination))
        upload.save(destination)

    return redirect(url_for('complete', uuid_key=uuid_key))

@app.route("/files/<uuid_key>")
def complete(uuid_key):
    location = "/static/uploads/{}".format(uuid_key)
    if not os.path.isdir(location):
        return "Error! {} not found!".format(location)

    files = []
    for file in glob.glob("{}/*.*".format(location)):
        fname = file.split(os.sep)[-1]
        files.append(fname)

    return render_template('complete.html', uuid=uuid_key, files=files)

complete.html

{% extends 'layout.html' %}

{% block content %}

{% for file in files %}
    <h2>{{ file }}</h2>
    <img src="{{ url_for('static', filename='/uploads/{}/{}'.format(uuid, file)) }}">
{% endfor %}

{% endblock %}

post.html

{% extends 'layout.html' %}

{% block content %}

    <form action="upload" method="post" enctype="multipart/form-data">
        <input type="file" name="file" accept="image/*"><br /><br />
        <input type="submit" value="Upload">
      </form>

{% endblock %}

我已经将我的代码与 kirsle 的代码进行了比较,但我看不出哪里出错了。

你在应该是相对路径的前面放了一个 /:

location = "static/uploads/{}".format(uuid_key)
    if not os.path.isdir(location):

假设您的文件结构是:

app.py
static/
templates/

这个逻辑在app.py