在使用Flask静态文件的时候,每次更新,发现CSS或是Js或者其他的文件不会更新。这是因为浏览器的缓存问题。

普遍大家是这几步解决办法。
清理浏览器缓存
设置浏览器不缓存
也有以下这么写的
1 2 3 4 5 6 7 8 9 10 | @app.context_processor
def override_url_for():
return dict(url_for=dated_url_for)
def dated_url_for(endpoint, **values):
if endpoint == 'static' :
filename = values.get( 'filename' , None)
if filename:
file_path = os.path.join(app.root_path, endpoint, filename)
values[ 'q' ] = int(os.stat(file_path).st_mtime)
return url_for(endpoint, **values)
|
如果是我,我不会这么做,效率很低。
这是 Flask的 config 的源码,里面可以看到,有设置缓存时间

SEND_FILE_MAX_AGE_DEFAULT 可以看到,它是一个 temedelta 的值
我们去更改配置。
第2行: 我们引入了datetime的timedelta对象
第6行: 我们配置缓存时间

这样就解决了缓存问题,不用去写多余的代码,不用去清理浏览器的缓存。
一定要学着去看官方文档和框架的源代码!!