如何在FastAPI中设置响应类?

问题描述 投票:0回答:2

使用或json序列化响应对fastAPIrestful服务的速度有显着影响,特别是对于非常大的对象。正如我在官方documentation中所读到的,我们可以直接使用响应类作为api方法的参数。问题是,当我直接使用

ORJSONResponse
作为函数时,它可以工作;但是,当将其传递给参数
esponse_class=ORJSONResponse
时,它不起作用。

1.直接调用
ORJSONResponse()
的示例代码:

此代码运行时间为75ms,大小6.6 MB,表明orjson序列化工作正常。 它比 .net core 更快,这正是我所需要的。

from fastapi import APIRouter

from fastapi.responses import ORJSONResponse

router=APIRouter()
__all__=["router"]

siz=1000000
ret=[None]*siz
for i in range(0,siz-1):
    ret[i]=i

@router.get("/planlist"))
def plan_list():
    ORJSONResponse(ret)
   

2.传递
ORJSONResponse
作为参数的示例代码:

此代码的运行就像没有设置响应类一样。在相同的6.6MB大小下,需要876毫秒多出10倍以上。它表明

orjson
尚未正确设置。

from fastapi import APIRouter
from fastapi.responses import ORJSONResponse

router=APIRouter()
__all__=["router"]

siz=1000000
ret=[None]*siz
for i in range(0,siz-1):
    ret[i]=i

@router.get("/planlist",response_class=ORJSONResponse)
def plan_list():

    for i in range(0,siz-1):
        ret[i]=i

    return ret

测试平台

  • 测试客户端:ansomnia core 2020.4.1,在postman 7.34.0中结果相同
  • 操作系统:MacOS catalina 10.15.7,Windows 10 的结果相同
  • CPU:酷睿i9
python serialization fastapi orjson
2个回答
4
投票

此外,我们还有关于 直接返回响应的文档。

所以你可以使用这个,这不是一个坏习惯。

return ORJSONResponse(content=data)

但这将跳过验证、序列化和自动文档,这将为您提供巨大的灵活性和性能,但这也意味着,您需要确保内容已准备好,并且需要手动设计 OpenAPI 模式。


0
投票

您现在可以使用 orjson 作为默认响应类/类型,如 docs

中所述

一个小例子

from fastapi import FastAPI
from fastapi.responses import ORJSONResponse

app = FastAPI(default_response_class=ORJSONResponse)


@app.get("/items/")
async def read_items():
    return [{"item_id": "Foo"}]
© www.soinside.com 2019 - 2024. All rights reserved.