【发布时间】:2021-08-19 08:06:51
【问题描述】:
我正在寻找类似于 Flask 的 app.config['JSONIFY_PRETTYPRINT_REGULAR'] = True 的东西。
【问题讨论】:
标签: python json fastapi pretty-print
我正在寻找类似于 Flask 的 app.config['JSONIFY_PRETTYPRINT_REGULAR'] = True 的东西。
【问题讨论】:
标签: python json fastapi pretty-print
这取自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")
【讨论】:
我不确定你的问题到底是什么,你能说出你需要什么背景吗?
但是,由于 FASTAPI 基于开放标准(OpenAPI、JSONSchema),它具有自动文档。 --> FastAPI Auto Docs.
您在 host/docs 下有 Swagger UI。 或 host/redoc 下的 ReDoc。 两者都可以轻松地为您提供 JSON 响应的漂亮表示。
【讨论】: