【问题标题】:How to convert dictionary to schema in FastAPI如何在 FastAPI 中将字典转换为模式
【发布时间】:2020-11-18 19:37:10
【问题描述】:

下面的模式可以使用branch.__dict__转换为dict

branch = BranchIn(name='jfslkjf', regionId='fdfasd')
branchDict = branch.__dict__
branchDict = {'name': 'jfslkjf', 'regionId': 'fdfasd' }

如何在 FastAPI 中再次将 dict 对象转换为模式

【问题讨论】:

  • 将dict转换为schema是什么意思。
  • 上述操作的逆向...

标签: python schema fastapi pydantic


【解决方案1】:

您可以使用双星号 ** 将多个变量解包为一个单个对象

class Branch(BaseModel):
    name: str
    regionID: str


def check_type(obj):
    return f"{obj}  \n  type: {type(obj)}"

我创建了这个类和类型检查器,然后我创建了分支对象

branch = Branch(name='jfslkjf', regionID='fdfasd')
check_type(branch)

Out: name='jfslkjf' regionID='fdfasd'  
     type: <class '__main__.Branch'>

然后我转换为字典

branch_dict = branch.__dict__
check_type(branch_dict)


Out: {'name': 'jfslkjf', 'regionID': 'fdfasd'}  
     type: <class 'dict'>

所以我用双星号来解压它

test_branch = Branch(**branch_dict)
check_type(test_branch)

Out: name='jfslkjf' regionID='fdfasd'  
     type: <class '__main__.Branch'>

【讨论】:

    【解决方案2】:

    您可以简单地将字典传播回Branch

    branchDict = {'name': 'jfslkjf', 'regionId': 'fdfasd' }
    branchObj = Branch(**branchDict)
    

    Fastapi 使用 pydantic。

    【讨论】:

      猜你喜欢
      • 2016-06-06
      • 2016-11-02
      • 2020-04-05
      • 1970-01-01
      • 2022-11-10
      • 2011-07-11
      • 2019-09-13
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多