python - 声明 Pydantic 模型“TypeError:‘type’对象不可迭代”
问题描述
我正在使用 FastAPI 构建数据 API。我希望客户发布 2 个 24 个浮点数的列表,稍后我将它们保存到数据库中。
当我尝试创建 Pydantic 模型时:
from pydantic import BaseModel
class Prices(BaseModel):
buying_price: list(float)=[]
selling_price: list(float)=[]
我收到以下错误:
File "c:/Users/Amin y Lubna/FastAPI-InfluxDB/test.py", line 3, in <module>
class Prices(BaseModel):
File "c:/Users/Amin y Lubna/FastAPI-InfluxDB/test.py", line 4, in Prices
buying_price: list(float)=[]
TypeError: 'type' object is not iterable
即使错误是不言自明的,我也不明白。
然后,查看文档,我发现了以下方式:
from pydantic import BaseModel
from typing import List
class Prices(BaseModel):
buying_price: List(float)=[]
selling_price: List(float)=[]
但我收到以下错误。
File "c:/Users/Amin y Lubna/FastAPI-InfluxDB/test.py", line 4, in <module>
class Prices(BaseModel):
File "c:/Users/Amin y Lubna/FastAPI-InfluxDB/test.py", line 5, in Prices
buying_price: List(float)=[]
File "C:\Users\Amin y Lubna\anaconda3\lib\typing.py", line 727, in __call__
raise TypeError(f"Type {self._name} cannot be instantiated; "
TypeError: Type List cannot be instantiated; use list() instead
几天来我一直在努力解决这个错误,但我无法找到解决问题的方法。
解决方案
你需要使用list[float]
,而不是list(float)
推荐阅读
- android - 如何修复错误:在类型对象上找不到参数 [目录'libs'] 的方法实现()
- excel-formula - 从单元格中提取特定的文本字符串
- c - 从指针访问值到指针
- google-chrome - 获取推送通知以在未运行时在桌面窗口上启动 Chrome
- http - Traefik - 将请求重定向到 AWS Lambda
- python - 我怎样才能建立一个非贪婪组
- bash - 难以在单行回声中提及多个呼叫
- python - 将 lambda 放入 NumPy `np.fromfunction()` 会导致 TypeError
- c++ - 如何将txt文件中的信息添加到哈希表
- c++ - 编写一个通用遍历函数,允许灵活处理具有不同参数的多个函数