【发布时间】:2023-01-12 06:30:41
【问题描述】:
我一直在为我的 /healthz 使用以下代码:
@router.get("/healthz", status_code=status.HTTP_204_NO_CONTENT, tags=["healthz"],
summary="Service for 'Health Check'",
description="This entrypoint is used to check if the service is alive or dead.",
# include_in_schema=False
)
def get_healthz() -> Response:
return Response(status_code=status.HTTP_204_NO_CONTENT)
这从几年前就开始工作了。
今天我将 FastAPI 从 0.88.0 更新到 0.89.0,现在我得到了AssertionError: Status code 204 must not have a response body。完整的 tracebakc 如下所示:
Traceback (most recent call last):
File "<frozen importlib._bootstrap>", line 1234, in _handle_fromlist
File "<frozen importlib._bootstrap>", line 241, in _call_with_frames_removed
File "......../src/routers/healthz.py", line 20, in <module>
@router.get("/healthz", status_code=status.HTTP_204_NO_CONTENT, tags=["healthz"],
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/Users/..../.local/share/virtualenvs/........../lib/python3.11/site-packages/fastapi/routing.py", line 633, in decorator
self.add_api_route(
File "/Users/..../.local/share/virtualenvs/......../lib/python3.11/site-packages/fastapi/routing.py", line 572, in add_api_route
route = route_class(
^^^^^^^^^^^^
File "/Users/...../.local/share/virtualenvs/....../lib/python3.11/site-packages/fastapi/routing.py", line 396, in __init__
assert is_body_allowed_for_status_code(
AssertionError: Status code 204 must not have a response body
python-BaseException
我的问题是:
这是版本 0.89.0 的错误,还是我应该以不同的方式编写 /heathz?
即使使用 return Response(status_code=status.HTTP_204_NO_CONTENT, content=None) 也是失败的。
谢谢
【问题讨论】:
-
我认为您没有按照说明进行操作。 FastAPI 自动构建响应,用户不应该明确地这样做。在您的特定情况下,FastAPI 将您返回的 Response 视为一个对象,并将该对象添加到自动构建的响应主体中。 :)
-
我刚刚看到这个修复在我提出问题后 1 小时打开,我将等待合并并再次测试:github.com/tiangolo/fastapi/pull/5860。如果问题无法解决,那么我将在此处提供有关我的实施的更多详细信息。仅供参考:@Chris alv2017