FastAPI升级至0.89.0后/healthz接口返回204报错咨询
FastAPI 0.89.0 204状态码断言错误解决办法
这不是版本bug,是FastAPI 0.89.0对HTTP规范的校验更严格了——HTTP 204 No Content状态码明确要求响应不能有任何内容体,哪怕是空的响应结构都不行。
之前用Response(status_code=status.HTTP_204_NO_CONTENT)或加content=None的写法,在0.89.0里会被判定为存在默认的空响应体(框架会自动添加Content-Type头并生成空JSON结构),触发断言错误。
正确的写法有两种:
- 直接返回状态码,不用包装成Response对象:
from fastapi import status, FastAPI app = FastAPI() @app.get("/healthz") async def health_check(): return status.HTTP_204_NO_CONTENT
- 若坚持用Response对象,必须显式设置
media_type="",且不指定content参数:
from fastapi import status, FastAPI, Response app = FastAPI() @app.get("/healthz") async def health_check(): return Response(status_code=status.HTTP_204_NO_CONTENT, media_type="")
这样就能符合HTTP 204的规范,避免断言错误。
内容的提问来源于stack exchange,提问作者Rui Martins
相关产品推荐
相关产品推荐

