如何用fastapi-cache缓存HTMLResponse?尝试方法仍报错
解决FastAPI-Cache2缓存HTMLResponse的问题
核心问题是默认编码器无法序列化HTMLResponse对象,且自定义编码器的实现或配置存在疏漏。以下是正确的实现步骤:
1. 完成缓存后端的基础初始化
先确保FastAPI-Cache2的后端配置正常,以内存缓存为例:
from fastapi import FastAPI, Request, HTMLResponse from fastapi_cache import FastAPICache from fastapi_cache.backends.inmemory import InMemoryBackend from fastapi_cache.decorator import cache from fastapi_cache.coder import Coder from typing import Any app = FastAPI() @app.on_event("startup") async def startup(): FastAPICache.init(InMemoryBackend())
2. 实现正确的HTMLResponse自定义编码器
你之前的编码器存在解码逻辑冗余问题,修正后的版本更简洁可靠:
class HTMLResponseCoder(Coder): @classmethod def encode(cls, value: Any) -> bytes: # 仅处理HTMLResponse类型,确保序列化的是原始响应体字节 if isinstance(value, HTMLResponse): return value.body # 非HTMLResponse类型可 fallback 到默认编码器(可选) return super().encode(value) @classmethod def decode(cls, value: bytes) -> Any: # 直接用原始字节初始化HTMLResponse,无需额外转义处理 return HTMLResponse(value)
3. 在路由缓存装饰器中指定编码器
在@cache装饰器里通过coder参数绑定自定义编码器:
@app.get("/", response_class=HTMLResponse) @cache(expire=60, coder=HTMLResponseCoder) async def read_items(request: Request, col=None, name: str = None): # 示例返回动态HTML内容 html_content = f""" <html> <body> <h1>Hello {name or "Guest"}!</h1> <p>Selected Column: {col or "None"}</p> </body> </html> """ return HTMLResponse(content=html_content)
额外优化:全局配置编码器
如果多个路由都需要缓存HTMLResponse,可以在初始化缓存时全局指定编码器,无需逐个路由配置:
@app.on_event("startup") async def startup(): FastAPICache.init(InMemoryBackend(), coder=HTMLResponseCoder)
内容的提问来源于stack exchange,提问作者Sam Marvasti
相关产品推荐
相关产品推荐

