gpt4 book ai didi

python - FastAPI 请求中的不可哈希类型

转载 作者:行者123 更新时间:2023-12-04 02:32:02 28 4
gpt4 key购买 nike

我正在使用 fastapi 编写 post-api。所需的请求格式为:

{
"leadid":LD123,
"parties":[
{
"uid":123123,
"cust_name":"JOhn Doe",
}, ...]}
python中的fastapi代码是:
class Customer(BaseModel):
UID: str
CustName: str

class PackageIn(BaseModel):
lead_id: str
parties: Set[Customer]
# threshold: Optional[int] = 85

app = FastAPI()

@app.post('/')
async def nm_v2(package:PackageIn):
return {"resp":"Response"}
当我访问 SwaggerUI 提交响应时,错误是 “422 错误:无法处理的实体” .此外,SwaggerUI 文档指出
{
"detail": [
{
"loc": [
"body"
],
"msg": "unhashable type: 'Customer'",
"type": "type_error"
}
]
}
我不知道如何为请求有效负载创建这个 dict() 结构而不创建一个名为 Customer 的单独的基于 pydantic 的类。请告诉我如何纠正错误。

最佳答案

Pytdantic BaseClass 不可散列。有一个discussion关于这个功能,我想它不会被实现。讨论中有解决方法,对于您的情况,您可以尝试以下操作:

from pydantic import BaseModel
from typing import Set


class MyBaseModel(BaseModel):
def __hash__(self): # make hashable BaseModel subclass
return hash((type(self),) + tuple(self.__dict__.values()))


class Customer(MyBaseModel): # Use hashable sublclass for your model
UID: str
CustName: str


class PackageIn(BaseModel):
lead_id: str
parties: Set[Customer]
# threshold: Optional[int] = 85

data = {
"lead_id": 'LD123',
"parties": [
{
"UID": 123123,
"CustName": "JOhn Doe",
}]}

PackageIn.parse_obj(data) # This part fastapi will make on post request, just for test

> <PackageIn lead_id='LD123' parties={<Customer UID='123123' CustName='JOhn Doe'>}>

关于python - FastAPI 请求中的不可哈希类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63721614/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com