我正在寻找类似于 Flask 的 app.config['JSONIFY_PRETTYPRINT_REGULAR'] = True
的东西。
我正在寻找类似于 Flask 的 app.config['JSONIFY_PRETTYPRINT_REGULAR'] = True
的东西。
以下内容摘自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")
async def streaming_output_json(content: List[BaseModel]) -> StreamingResponse:
"""
Convert a list of Pydantic models to a JSON StreamingResponse.
"""
async def jsonify_async(models: List[BaseModel]) -> AsyncIterable[str]:
yield '['
for i, model in enumerate(models):
await asyncio.sleep(0)
if i > 0:
yield ','
result_dict = jsonable_encoder(model)
serialized_dict = json.dumps(result_dict)
yield serialized_dict
yield ']'
return StreamingResponse(jsonify_async(models=content), media_type='application/json')
@router.get("")
async def get_huge_result():
results = [model1, model2, ...]
return await streaming_output_json(results)
ORJSONResponse
。只需将输出扔到 ORJSONResponse(streaming_output_json(results))
中即可工作。希望 ORJSONResponse
不会将其重新格式化为单行。哈哈 - DataMinion我不确定你的问题具体是什么,你能告诉我你需要的背景吗?
然而,由于FASTAPI基于开放标准(OpenAPI,JSONSchema),它具有自动文档。--> FastAPI自动文档。
你可以在host/docs下找到Swagger UI, 或者在host/redoc下找到ReDoc。 两者都会以简单易懂的方式呈现JSON响应的漂亮表示。