關(guān)于flask中css無法自動更新的問題

最近在用flask坐網(wǎng)站的時候發(fā)現(xiàn),如果修改了css或js文件,不論是重啟服務(wù)器還是刷新頁面都不會有反應(yīng), 上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無法自動更新的問題。
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容