FastAPI 请求中不可散列的类型
Unhashable type in FastAPI request
我正在使用 fastapi 编写 post-api。所需的请求格式为:
{
"leadid":LD123,
"parties":[
{
"uid":123123,
"cust_name":"JOhn Doe",
}, ...]}
python中的快速api代码是:
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"
}
]
}
我不知道如何在不创建一个单独的基于 pydantic 的 class 名为 Customer 的情况下为请求负载创建此 dict() 结构。请告诉我如何纠正错误。
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'>}>
我正在使用 fastapi 编写 post-api。所需的请求格式为:
{
"leadid":LD123,
"parties":[
{
"uid":123123,
"cust_name":"JOhn Doe",
}, ...]}
python中的快速api代码是:
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"
}
]
}
我不知道如何在不创建一个单独的基于 pydantic 的 class 名为 Customer 的情况下为请求负载创建此 dict() 结构。请告诉我如何纠正错误。
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'>}>