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

Is there a way to pretty print / prettify a JSON response in FastAPI?

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

我不确定你的问题到底是什么,你能说说你需要什么背景吗?

但是,由于 FASTAPI 基于开放标准(OpenAPI,JSONSchema),因此它具有自动文档。 --> FastAPI Auto Docs.

您在 host/docs 下有 Swagger UI。 或 host/redoc 下的 ReDoc两者都会轻松地为您提供 JSON 响应的漂亮表示。

这取自David Montague

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

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

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")