【问题标题】:How to read the request body using orjson library in FastAPI?如何使用 FastAPI 中的 orjson 库读取请求体?
【发布时间】:2022-12-31 03:43:21
【问题描述】:

我正在编写代码以在 FastAPI 中接收 JSON 负载。

这是我的代码:

from fastapi import FastAPI, status, Request
from fastapi.responses import ORJSONResponse
import uvicorn
import asyncio
import orjson

app = FastAPI()

@app.post("/", status_code = status.HTTP_200_OK)
async def get_data(request: Request):
    param = await request.json()
    return param

但是,我想要的是 request.json()orjson 一起使用,而不是 Python 的默认 json 库。 知道如何解决这个问题吗?请帮助我,谢谢。

【问题讨论】:

标签: python fastapi starlette orjson


【解决方案1】:

使用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数据

当返回 dictlist 等数据时,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 序列化)。查看更多文档herehere 了解如何定制和/或将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)

请务必查看herehere以及herehere,以了解将 JSON 数据发送到 FastAPI 后端的各种方法,以及如何定义端点以进行预期和验证JSON 数据,而不是依赖于使用 await request.json()(这在应用程序需要传递任意 JSON 数据但不对数据执行任何验证时很有用)。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2023-02-10
    • 1970-01-01
    • 1970-01-01
    • 2022-11-27
    • 1970-01-01
    • 2021-07-14
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多