[英]How to JSON serialize ENum classes in Pydantic BaseModel
I have the following code that uses Pydantic BaseModel data class我有以下使用 Pydantic BaseModel 数据类的代码
from enum import Enum
import requests
from pydantic import BaseModel
from requests import Response
class PetType(Enum):
DOG: str = 'dog'
CAT: str = 'cat'
class Pet(BaseModel):
name: str
type: PetType
my_dog: Pet = Pet(name='Lucky', type=PetType.DOG)
# This works
resp: Response = requests.post('https://postman-echo.com/post', json=my_dog.json())
print(resp.json())
#This doesn't work
resp: Response = requests.post('https://postman-echo.com/post', json=my_dog.dict())
print(resp.json())
That when I send json equals to model's dict(), I get the error:当我发送 json 等于模型的 dict() 时,出现错误:
> TypeError: Object of type 'PetType' is not JSON serializable > TypeError: 'PetType' 类型的对象不是 JSON 可序列化的
How do I overcome this error and make PetType also serializable?如何克服此错误并使 PetType 也可序列化?
PS The above example is short and simple, but I hit a use case where both cases of sending PS上面的例子简短而简单,但我遇到了一个用例,其中两种发送情况
json=my_dog.json()
and和
json=my_dog.dict()
don't work.不工作。 This is why I need to solve sending using dict()
这就是为什么我需要使用 dict() 解决发送
Turns out that this is a behavior of ENum, which is discussed here: https://github.com/samuelcolvin/pydantic/issues/2278原来这是 ENum 的一种行为,这里讨论: https : //github.com/samuelcolvin/pydantic/issues/2278
The way you should define the enum is using您应该定义枚举的方式是使用
class PetType(str, Enum):
instead of代替
class PetType(Enum):
For integers this Python's Enum library provides the type IntEnum: https://docs.python.org/3.10/library/enum.html#enum.IntEnum对于整数,此 Python 的 Enum 库提供 IntEnum 类型: https ://docs.python.org/3.10/library/enum.html#enum.IntEnum
which is basically这基本上是
class IntEnum(int, Enum):
pass
If you look at the above Enum documentation you will find that a type like StrEnum doesn't exist but following the example for PetType you can define it easily.如果您查看上面的 Enum 文档,您会发现像 StrEnum 这样的类型不存在,但是按照 PetType 的示例,您可以轻松定义它。
I am attaching the working code below我附上下面的工作代码
from enum import Enum
import requests
from pydantic import BaseModel
from requests import Response
class PetType(str, Enum):
DOG: str = 'dog'
CAT: str = 'cat'
class Pet(BaseModel):
name: str
type: PetType
my_dog: Pet = Pet(name='Lucky', type=PetType.DOG)
# This works
resp: Response = requests.post('https://postman-echo.com/post', json=my_dog.json())
print(resp.json())
# Now this also works
resp: Response = requests.post('https://postman-echo.com/post', json=my_dog.dict())
print(resp.json())
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.