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

时间:2015-12-16 04:15:05

标签: python python-3.x flask uuid glob

我正在尝试创建一个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 %}似乎无法运行,因为没有任何图片显示。

我的代码是:

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的代码进行了比较,我看不出哪里出错了。

1 个答案:

答案 0 :(得分:2)

您已将PRIMARY KEY放在应该是相对路径的前面:

/

假设您的文件结构是:

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

这个逻辑在app.py