如果我不清除缓存,为什么我的 Flask 应用程序不呈现 CSS?

如果我不清除缓存,为什么我的 Flask 应用程序不呈现 CSS?

问题描述:

我一直在使用 Flask 并将我渲染的 html 链接到 css 样式表.我注意到每当我更新 CSS 代码时,我都必须清除缓存才能让它在网页上更新.我该如何解决这个问题?

I've been using Flask and have linked the html I'm rendering to a css stylesheet. I've noticed that whenever I update my CSS code, I have to clear the cache in order to get it to update on the webpage. How can I fix this?

我假设您正在加载 CSS 文件,例如:

I assume you are loading your CSS files with something like:

{{ url_for('static', filename='some/file.css') }}

为了在开发中立即刷新,您应该将以下配置变量设置为 -1:

For this to refresh immediately in development, you should set the following config var to -1:

app.config['SEND_FILE_MAX_AGE_DEFAULT'] = -1

正如@Matvei 所说,这个问题更多地与您的浏览器有关.要可视化这一点,请打开开发工具,转到网络 选项卡并突出显示特定的 CSS 文件.然后在右侧的部分中,在 Headers -> Response Headers 下查找以下行:

As @Matvei states, this issue is more to do with your browser. To visualise this, open the dev tools, go to the Network tab and highlight the specific CSS file. Then in the section on the right look for the following line under Headers -> Response Headers:

Cache-Control: public, max-age=-1

如果设置已正确应用,则应显示 -1.如果它显示任何其他内容,您需要刷新该特定文件,直到它显示 -1,可能需要清除缓存.这是因为浏览器根据 Cache-Control 标头来选择是否重新加载文件.

If the setting has been applied correctly this should show -1. If it shows anything else you need to refresh that specific file, until it does show -1, possibly having to clear your cache. This is because the browser makes the choice of whether to reload the file based on the Cache-Control header.

请参阅我的类似答案,并附上屏幕截图和文档链接.

See my similar answer on this with screencaps and links to the docs.