关于flask中css无法自动更新的问题

最近在用flask坐网站的时候发现,如果修改了css或js文件,不论是重启服务器还是刷新页面都不会有反应, 上stackoverflow上面查了之后说是浏览器缓存的问题。

[Flask css not updating [closed] - stackoverflow

这是采纳的解释:

Problem is, as already said, related to browser cache.
To solve that, you could add some dynamic variable to your static (css, js) links. I prefer last modified timestamp for each file.
/static/css/style.css?q=1280549780

Here is a snippet for that:
http://flask.pocoo.org/snippets/40/

点开那个链接之后可以看到

static url cache buster
Posted by ericbuckley on 2010-09-24 @ 23:02 and filed in URLs

If you decide to add an expires header (and if you haven't already you really should) to your static resources, you now need to worry about cache busting these resources after your next deploy. A simple way of dealing with this is to add a last modified query parameter to the end of your resource. For example:

<link rel="stylesheet" href="/static/css/reset.css?q=1280549780" type="text/css" media="screen" charset="utf-8" />

By adding the following snippet you can override the default url_for(endpoint, **values)
variable in your template context. Now any time you use url_for
in your templates to render a static resource it will be appended with a last modified time stamp parameter.

@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)


> This snippet by ericbuckley can be used freely for anything you like. Consider it public domain.

通过重写url_for,可以在后面加入时间戳,就可以解决css和js无法自动更新的问题。
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容