使用orjson读取request数据
在调用await request.json()时,FastAPI(实际上是Starlette)首先读取body(使用Request对象的.body()方法),然后调用json.loads()(使用Python的标准json库)返回一个dict/list 在端点内向您发送对象(请参阅实现 here)—它不使用 .dumps(),正如您在 cmets 部分中提到的,因为该方法用于将 Python 对象序列化为JSON。
因此,要使用 orjson 读取/转换请求正文,您可以使用以下内容(如果您想在 def 而不是 async def 端点中检索原始正文,请查看 this answer ):
from fastapi import FastAPI, Request
import orjson
app = FastAPI()
@app.post('/')
async def submit(request: Request):
body = await request.body()
data = orjson.loads(body)
return 'success'
使用orjson返回response数据
当返回 dict、list 等数据时,FastAPI 会使用 Python 标准 json.dumps() 自动将该返回值转换为 JSON,在检查其中的每个项目并确保它可以使用 JSON 序列化后,使用 @ 987654323@(有关详细信息,请参阅this answer)。因此,如果您想改用 orjson 库,则需要直接发送自定义的 Response,如 this answer 中所述。例子:
from fastapi import FastAPI, Request
import orjson
app = FastAPI()
@app.post('/')
async def submit(request: Request):
body = await request.body()
data = orjson.loads(body)
return Response(orjson.dumps(data), media_type='application/json')
或者,您可以使用 FastAPI 提供的 use the ORJSONResponse(仍然确保您安装了 orjson 库,以及您返回的内容可以使用 JSON 序列化)。查看更多文档here 和here 了解如何定制和/或将ORJSONResponse设置为默认响应类(ORJSONResponse的实现可以在here找到)。例子:
from fastapi import FastAPI
from fastapi.responses import ORJSONResponse
app = FastAPI()
@app.post('/', response_class=ORJSONResponse)
async def submit(request: Request):
body = await request.body()
data = orjson.loads(body)
return ORJSONResponse(data)
请务必查看here、here以及here和here,以了解将 JSON 数据发送到 FastAPI 后端的各种方法,以及如何定义端点以进行预期和验证JSON 数据,而不是依赖于使用 await request.json()(这在应用程序需要传递任意 JSON 数据但不对数据执行任何验证时很有用)。