pydantic如何使用pydantic设置十六进制字符串?
有时,任何数据都会返回像“ BBB”这样的十六进制字符串。我想用“ bbb”来估算。 所以我写了代码案例1 ..但这是一个错误。
如何使用basemodel将十六进制字符串转换为int值? Pydantic是否还具有Setter Getter函数? 我知道像case2这样的方法,但是我想直接使用JSON数据,因为某些密钥是空的...!
案例1
from pydantic import BaseModel
from typing import Optional
data = {
"aaa" : 4,
"bbb" : "0x3",
}
class DataTemp(BaseModel):
aaa : int
bbb : Optional[int]
def main():
_data = DataTemp(**data)
print(_data)
if __name__ == "__main__":
main()
案例2
_data2 = DataTemp(aaa= data["aaa"], bbb=int(data["bbb"],16))
Sometimes, any data return a hex string like "bbb". I wanna use to int value by "bbb".
So I wrote code case1.. but it is an error.
How to convert hex string to int value using BaseModel?
Does pydantic also have a setter getter function?
I know a method like case2, but I wanna use a json data directly, because of some key is empty...!
case 1
from pydantic import BaseModel
from typing import Optional
data = {
"aaa" : 4,
"bbb" : "0x3",
}
class DataTemp(BaseModel):
aaa : int
bbb : Optional[int]
def main():
_data = DataTemp(**data)
print(_data)
if __name__ == "__main__":
main()
case2
_data2 = DataTemp(aaa= data["aaa"], bbb=int(data["bbb"],16))
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
根据他们的迁移指南的这一部分 此先前的修订版。。
pydantic确实允许通过现场验证器。创建一个时,您需要注意处理传入的数据并根据您的要求处理。在您的示例中,它应允许
无
,标准int
s以及代表十六进制字符串的任何str
。因此,以下实施可以满足上述约束:用法:
This answer has been updated for Pydantic V2 (specifically 2.5.x) as per the this section of their migration guide while maintaining the original intent of this prior revision.
Pydantic does allow the attachment of additional validators to a given field by via field validators. When creating one you will need to take care to deal with the incoming data and process it based on your requirements. In your example, it should allow
None
, standardint
s and also anystr
that represent a hexadecimal string. So the following implementation can satisfy the mentioned constraints:Usage: