Flask:在静态文件上设置标头

7

我有下面这个 Flask 路由,可以提供静态内容:

@app.route('/static/<path:path>')
@resourceDecorator
def getStaticFile(path):
    return send_from_directory('static', path)

@resourceDecorator的声明如下:

def resourceDecorator(f):
    def new_func(*args, **kwargs):
        resp = make_response(f(*args, **kwargs))

        resp.cache_control.no_cache = True                   # Turn off caching
        resp.headers['Access-Control-Allow-Origin'] = '*'    # Add header to allow CORS

        return resp
    return update_wrapper(new_func, f)

装饰器设置头部以取消缓存并允许跨域访问,这适用于我的其他“常规”路由,但通过静态路由发送的文件似乎没有设置其头部。
出了什么问题?

您能自省 getStaticFile 视图返回的对象类型吗?它是否与 make_response 函数所期望的类型之一相同?我在这里有些疑惑,因为 send_from_directory 返回了一些特殊的对象。 - shreyas
1个回答

1
对于静态文件,Flask将默认缓存超时设置为12小时/43200秒,因此出现了您的问题。您可以通过直接传递cache_timeout值来更改send_from_directory中的默认缓存超时,因为它使用send_file函数将文件发送到客户端。
send_from_directory(cache_timeout=0)

或者您可以覆盖get_send_file_max_age


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接