如何配置Starlette取消设置Cache-Control: no-cache响应头?
解决Starlette静态文件发送
Cache-Control: no-cache的问题 方法一:关闭Debug模式
当你设置debug=True时,Starlette会自动为静态文件添加no-cache缓存头,用于开发环境实时更新文件。如果是生产环境,直接将debug改为False即可:
app = Starlette(debug=False, routes=routes, middleware=middleware)
关闭debug后,StaticFiles会使用默认的缓存策略(通常是Cache-Control: public, max-age=600),不再发送no-cache头。
方法二:自定义缓存头(保留Debug模式)
如果需要保留debug模式同时修改缓存策略,可以通过StaticFiles的参数或自定义类来调整:
方式1:直接设置cachecontrol参数
在挂载StaticFiles时,指定cachecontrol值覆盖默认设置:
routes = [ Mount('/', app=StaticFiles(directory=DIST_DIR, cachecontrol="public, max-age=3600"), name="static"), ]
这样所有静态文件都会使用你指定的Cache-Control头,不会再带no-cache。
方式2:继承StaticFiles自定义缓存逻辑
如果需要更灵活的控制(比如不同文件类型设置不同缓存策略),可以继承StaticFiles并重写get_response方法:
from starlette.staticfiles import StaticFiles class CustomStaticFiles(StaticFiles): def get_response(self, path: str, scope): response = super().get_response(path, scope) # 删除默认的no-cache和Pragma头 response.headers.pop("Cache-Control", None) response.headers.pop("Pragma", None) # 添加自定义缓存规则 response.headers["Cache-Control"] = "public, max-age=3600" return response # 替换原有的StaticFiles routes = [ Mount('/', app=CustomStaticFiles(directory=DIST_DIR), name="static"), ]
通过以上方法,就能移除no-cache响应头,解决桌面版Office加载项图标无法显示的问题。
内容的提问来源于stack exchange,提问作者AndreA
相关产品推荐
相关产品推荐

