使用Flask重定向到静态目录中的资源文件

时间:2014-12-03 22:30:36

标签: python flask

我有一个包含一些资源(数据文件)的静态目录,我可以直接访问这些文件:即http://hello.com/static/dir/abc.pdf。但是,我在目录中收到错误地址:即http://hello.com/static/dir

使用flask,我可以通过显示目录的内容来解决这个问题。

@app.route('/static/<path:url>') @protect 
def show(url):
    content_dir = app.config['CONTENT_DIR']
    directory = "%s/%s/box/%s" % (content_dir, url, url2)
    result = []

    if os.path.isdir(directory):
        for file in os.listdir(directory):
            content['url'] = '/static/...
        result.append(content)
    return render_template("box.html",...)

问题在于,通过此路由处理,直接文件访问不再起作用,因为http://hello.com/static/dir/abc.pdf始终触发show()方法。

如何重定向到资源文件(示例中的abc.pdf),而不是重定向到show()方法?

1 个答案:

答案 0 :(得分:1)

在自定义静态路由中,检查路径是文件还是目录。如果是文件,请提供,否则显示目录索引。

import os
from flask import send_file

path = os.path.join(app.config['CONTENT_DIR'], url, 'box', url2)

if os.path.isfile(path):
    return send_file(path)

return render_template('box.html', ...)

当然,由于路径是由用户发送的网址指定的,因此您应首先检查它是否安全。