在starlette中设置缓存控制,最直接的方法是在响应对象上修改 headers 字典,将 cache-control 键的值设为你需要的策略字符串。例如,调用 response.headers["cache-control"] = "no-cache" 即可禁止浏览器缓存。你也可以通过中间件统一处理所有响应,或者在路由函数中直接操作返回的 response 实例。

如何在单个路由中为特定响应设置私有缓存?
要在单个路由中设置私有缓存(即只缓存给特定用户,不共享),你需要创建一个 Response 对象并显式添加 Cache-Control: private, max-age=3600 头。这通常用于包含用户个性化数据的页面,防止CDN或公共代理缓存敏感内容。只需在视图函数中实例化 starlette.responses.Response,并在初始化时或通过属性赋值设置头部即可。

from starlette.applications import Starlette
from starlette.responses import Response
from starlette.routing import Route
async def homepage(request):
# 创建响应,设置私有缓存,最大存活时间1小时
response = Response(
content="Hello, this is a private page.",
media_type="text/plain"
)
response.headers["Cache-Control"] = "private, max-age=3600"
return response
routes = [
Route("/", endpoint=homepage),
]
app = Starlette(routes=routes)
当访问 / 路径时,响应头中将包含 Cache-Control: private, max-age=3600。浏览器会缓存该页面,但不会将其存储在共享缓存中。其他用户请求同一URL时,将从服务器获取最新内容,而不是从共享缓存读取。这确保了用户特定的数据不会被错误地共享。
Starlette 1.5.1 是轻量级 Python ASGI 框架与工具集,提供路由、请求响应、中间件、WebSocket 和后台任务等组件,适合构建异步 Web 服务。本下载为官方 PyPI 通用 wheel 包,可使用 pip 安装,并由包管理器处理依赖;运行应用时还需配置 ASGI 服务器。
如何使用中间件全局禁用所有静态资源的缓存?
如果需要全局禁用某些资源(如开发环境下的JS/CSS)的缓存,可以编写一个自定义中间件,拦截所有响应并覆盖 Cache-Control 头。这种方法比在每个路由中手动设置更高效且不易遗漏。中间件会在响应发送前修改头部,确保所有经过它的请求都应用统一的缓存策略。

from starlette.applications import Starlette
from starlette.middleware import Middleware
from starlette.middleware.base import BaseHTTPMiddleware
from starlette.responses import Response
from starlette.routing import Route
class NoCacheMiddleware(BaseHTTPMiddleware):
async def dispatch(self, request, call_next):
response = await call_next(request)
# 仅对文本类资源禁用缓存,避免影响图片等二进制文件
if response.headers.get("content-type", "").startswith("text/"):
response.headers["Cache-Control"] = "no-store, no-cache, must-revalidate"
return response
async def dummy(request):
return Response(content="Dummy text", media_type="text/plain")
routes = [Route("/dummy", endpoint=dummy)]
app = Starlette(
routes=routes,
middleware=[Middleware(NoCacheMiddleware)]
)
启动应用后,访问 /dummy 将返回带有 Cache-Control: no-store, no-cache, must-revalidate 头的响应。这告诉浏览器和任何中间代理不要存储该响应的任何副本。每次请求都必须重新向服务器验证或获取内容。这种中间件方式适用于开发调试或需要严格实时性的场景,避免了逐个路由配置的繁琐。
如果同时设置了Cache-Control和Expires头,浏览器优先使用哪个?
当 Cache-Control 和 Expires 头同时存在时,HTTP/1.1 规范规定 Cache-Control 具有更高的优先级。浏览器会忽略 Expires 头,仅依据 Cache-Control 中的指令进行缓存决策。这意味着如果你设置了 Cache-Control: no-cache,即使 Expires 指向未来某个时间,浏览器也不会使用缓存副本,而是重新验证。这种优先级关系确保了更精细、更现代的缓存控制机制能够覆盖旧的基于时间的策略。

















