pydantic重复使用的词典的键和值
如何验证输入以获取以下dict
传递!
d = dict()
d['en'] = 'English content'
d['it'] = 'Italian content'
d['es'] = 'Spanish content'
print(d)
# {'en': 'English content', 'it': 'Italian content', 'es': 'Spanish content'}
在此示例中,密钥是ISO 639-1代码
使用pycountry
python软件包。
code = 'en'
pycountry.languages.get(alpha_2=code.upper()).alpha_2 # = 'en'
关键是如何使用Pydantic可重复使用的验证器或任何其他方法来验证键? 并验证值要么是str
或int
? Pydantic Model 架构
应与此示例相似:
# products/model.py
from sqlalchemy import Column, String, Integer
from sqlalchemy.ext.declarative import declarative_base
from custom_field import Translatable
Base = declarative_base()
class Model(Base):
__tablename__ = "products"
id = Column(Integer, unique=True, index=True)
name = Column(Translatable())
price = Column(Integer)
# products/pydantic.py
from pydantic import BaseModel
import custom_pydantic_field
class BaseSchema(BaseModel):
id: int
class CreateSchema(BaseSchema):
name: custom_pydantic_field.translatable
price: int
在其他模型/架构中牢记可重复使用性。
How to validate input to get the following Dict
passed!
d = dict()
d['en'] = 'English content'
d['it'] = 'Italian content'
d['es'] = 'Spanish content'
print(d)
# {'en': 'English content', 'it': 'Italian content', 'es': 'Spanish content'}
In this example, keys are ISO 639-1 codes
using pycountry
python package.
code = 'en'
pycountry.languages.get(alpha_2=code.upper()).alpha_2 # = 'en'
The point is how to validate keys using pydantic reusable validator or any other methods?
And validate values either to be str
or int
?
Pydantic model schema
should be similar to this sample :
# products/model.py
from sqlalchemy import Column, String, Integer
from sqlalchemy.ext.declarative import declarative_base
from custom_field import Translatable
Base = declarative_base()
class Model(Base):
__tablename__ = "products"
id = Column(Integer, unique=True, index=True)
name = Column(Translatable())
price = Column(Integer)
# products/pydantic.py
from pydantic import BaseModel
import custom_pydantic_field
class BaseSchema(BaseModel):
id: int
class CreateSchema(BaseSchema):
name: custom_pydantic_field.translatable
price: int
Keep in mind reusability in other models/schemas.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
创建 pydantic 自定义类
然后在您的 schema/pydantic 模型中使用它,例如:
并在 SQLALchemy 模型中使用正常的
JSON
字段!Create pydantic custom class
Then use it in you schema/pydantic model like:
And use normal
JSON
field in SQLALchemy model!