【问题标题】:Is there a way to pretty print / prettify a JSON response in FastAPI?有没有办法在 FastAPI 中漂亮地打印/美化 JSON 响应?
【发布时间】:2021-08-19 08:06:51
【问题描述】:

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

【问题讨论】:

    标签: python json fastapi pretty-print


    【解决方案1】:

    这取自David Montague

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

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

    【讨论】:

      【解决方案2】:

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

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

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2011-09-29
        • 1970-01-01
        • 2020-09-16
        • 1970-01-01
        • 1970-01-01
        • 2015-12-11
        • 1970-01-01
        相关资源
        最近更新 更多