【问题标题】:FastAPI - Cannot use `Response` as a return type when `status_code` is set to 204FastAPI - 当“status_code”设置为 204 时,不能使用“Response”作为返回类型
【发布时间】: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) 也是失败的。

0.89.0 的变更日志:

谢谢

【问题讨论】:

  • 我认为您没有按照说明进行操作。 FastAPI 自动构建响应,用户不应该明确地这样做。在您的特定情况下,FastAPI 将您返回的 Response 视为一个对象,并将该对象添加到自动构建的响应主体中。 :)
  • 我刚刚看到这个修复在我提出问题后 1 小时打开,我将等待合并并再次测试:github.com/tiangolo/fastapi/pull/5860。如果问题无法解决,那么我将在此处提供有关我的实施的更多详细信息。仅供参考:@Chris alv2017

标签: python fastapi


【解决方案1】:

【讨论】:

    猜你喜欢
    • 2022-10-18
    • 2022-01-22
    • 2014-09-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-12-09
    • 2019-07-01
    相关资源
    最近更新 更多