zoukankan      html  css  js  c++  java
  • FastAPI 进阶知识(二) JSON兼容编码

    作者:麦克煎蛋   出处:https://www.cnblogs.com/mazhiyong/ 转载请保留这段声明,谢谢!

    在进行数据存储或者传输的时候,有时候我们需要把数据(比如Pydantic模型)转换成JSON兼容的格式(如dict、list等)。

    FastAPI提供了 jsonable_encoder 函数来实现。

    from datetime import datetime
    
    from fastapi import FastAPI
    from fastapi.encoders import jsonable_encoder
    from pydantic import BaseModel
    
    
    class Item(BaseModel):
        title: str
        timestamp: datetime
        description: str = None
    
    
    app = FastAPI()
    
    
    @app.put("/items/{id}")
    def update_item(id: str, item: Item):
        json_compatible_item_data = jsonable_encoder(item)
    print(json_compatible_item_data)

    在上面的示例中,如果Request Body为:

    {
        "title": "title",
        "timestamp": "2017-11-23 16:10:10"
    }

    那么打印结果为:

    {'title': 'title', 'timestamp': '2017-11-23T16:10:10', 'description': None}

    这里 jsonable_encoderdatetime 转换成了字符串,而把Pydantic模型转换成了dict格式。

    其他类型的数据转换可自行尝试。

  • 相关阅读:
    bzoj 5455
    hdu 6705
    hdu 6706
    斜率优化
    bzoj3672
    bzoj1367
    bzoj2118
    bzoj2337
    Codeforces 1077D Cutting Out(二分答案)
    Codeforces 1079C Playing Piano(记忆化搜索)
  • 原文地址:https://www.cnblogs.com/mazhiyong/p/12965542.html
Copyright © 2011-2022 走看看