zoukankan      html  css  js  c++  java
  • FastAPI(49)- 自定义响应之 ORJSONResponse、UJSONResponse

    更多自定义响应类型

    ORJSONResponse

    作用

    • 如果需要提高性能,可以安装并使用 orjson,并将响应设置为 ORJSONResponse
    • 官方介绍:快速、正确的 Python JSON 库,支持 dataclass、datetime、numpy
    • 注意:仅在 FastAPI 才支持 ORJSONResponse,Starlette 并没有它
    pip install orjson

    response_class

    可以在路径操作装饰器上声明 response_class=Response ,然后最终返回的响应数据的类型就是声明的 Response

    实际代码

    from fastapi import FastAPI
    from fastapi.responses import ORJSONResponse
    
    app = FastAPI()
    
    
    # 声明返回的 Response 类型
    @app.get("/item", response_class=ORJSONResponse)
    async def get_item():
        return [{"item_id": "Foo"}]
    • response_class 将用于定义响应的 media_type
    • 上面的栗子中,Response Header 的 Content-type 将为 application/json,并且会记录在 OpenAPI 中

    查看 Swagger API 文档的 Response Header

    请求结果

    源码

    用的是 orjson 的 dumps() 方法

    UJSONResponse

    和 ORJSONResponse 一样的用法,更推荐用 orjson 代替 ujson

  • 相关阅读:
    索引压缩
    拼写校正
    词典(词汇表)
    Text Relatives II
    Text Relatives
    CoreText
    Quartz2D Text
    PDF Document Creation, Viewing
    Core Graphics Layer Drawing
    Bitmap Images and Image Masks
  • 原文地址:https://www.cnblogs.com/poloyy/p/15364980.html
Copyright © 2011-2022 走看看