有没有办法在 FastAPI 中漂亮地打印/美化 JSON 响应?

New*_*der 6 python json pretty-print fastapi

我正在寻找类似于 Flask 的东西app.config['JSONIFY_PRETTYPRINT_REGULAR'] = True

Wol*_*ehn 13

这是取自大卫·蒙塔古

您可以使用自定义响应类来注释任何端点,例如

@app.get("/config", response_class=PrettyJSONResponse)
def get_config() -> MyConfigClass:
    return app.state.config
Run Code Online (Sandbox Code Playgroud)

一个例子PrettyJSONResponse可能是(indent=4就是你所问的)

import json, typing
from starlette.responses import Response

class PrettyJSONResponse(Response):
    media_type = "application/json"

    def render(self, content: typing.Any) -> bytes:
        return json.dumps(
            content,
            ensure_ascii=False,
            allow_nan=False,
            indent=4,
            separators=(", ", ": "),
        ).encode("utf-8")
Run Code Online (Sandbox Code Playgroud)

  • 请记住,PrettyJSONResponse 会阻止大型数据集上的异步函数,因此需要谨慎使用,否则在某些情况下会导致性能问题。 (4认同)