pydantic重复使用的词典的键和值

发布于 2025-01-19 18:31:26 字数 1320 浏览 2 评论 0原文

如何验证输入以获取以下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可重复使用的验证器或任何其他方法来验证? 并验证要么是strint? 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

甜味拾荒者 2025-01-26 18:31:26

创建 pydantic 自定义类

# validators/translated_field.py
from typing import Dict
from pydantic import ValidationError
from pydantic.error_wrappers import ErrorWrapper
import pycountry

class Translatable(Dict):
    """
    Validate Translation Dict Field (Json) where Language is Key and Translation as Value
        Languages : ISO 639-1 code
        Translation : Int, str, None

    ref:
    - https://pydantic-docs.helpmanual.io/usage/types/#classes-with-__get_validators__

    By: Khalid Murad
    """

    @property
    def __translation_interface__(self):
        return self.dict()

    @classmethod
    def __get_validators__(cls):
        yield cls.validate

    @classmethod
    def validate(cls, base_dictionary):
        result = dict()
        dictionary = dict()
        errors = []

        dictionary = base_dictionary

        for key in dictionary:
            try:
                parsed_language = pycountry.languages.get(alpha_2=key.upper())
            except ValueError as exc:
                errors.append(ErrorWrapper(Exception(f"Invalid language: {key}."), loc="language"))
            if not parsed_language:
                errors.append(ErrorWrapper(Exception(f"Invalid language: {key}."), loc="language"))
            if isinstance(dictionary[key], int | str | None):
                result[key] = dictionary[key]
            else:
                errors.append(ErrorWrapper(Exception(f"Invalid content for language: {key}."), loc=("language","content")))

        if errors:
            raise ValidationError(
            errors,
            cls,
            )

        return cls(result)

然后在您的 schema/pydantic 模型中使用它,例如:

# products/pydantic.py
from pydantic import BaseModel
from validators.translated_field import Translatable

class BaseSchema(BaseModel):
    id: int

class CreateSchema(BaseSchema):
    name: Translatable
    ...your code

并在 SQLALchemy 模型中使用正常的 JSON 字段!

# products/model.py
...
from sqlalchemy import Column, JSON
...
class Model(Base):
    name = Column(JSON, nullable=True)
    ...

Create pydantic custom class

# validators/translated_field.py
from typing import Dict
from pydantic import ValidationError
from pydantic.error_wrappers import ErrorWrapper
import pycountry

class Translatable(Dict):
    """
    Validate Translation Dict Field (Json) where Language is Key and Translation as Value
        Languages : ISO 639-1 code
        Translation : Int, str, None

    ref:
    - https://pydantic-docs.helpmanual.io/usage/types/#classes-with-__get_validators__

    By: Khalid Murad
    """

    @property
    def __translation_interface__(self):
        return self.dict()

    @classmethod
    def __get_validators__(cls):
        yield cls.validate

    @classmethod
    def validate(cls, base_dictionary):
        result = dict()
        dictionary = dict()
        errors = []

        dictionary = base_dictionary

        for key in dictionary:
            try:
                parsed_language = pycountry.languages.get(alpha_2=key.upper())
            except ValueError as exc:
                errors.append(ErrorWrapper(Exception(f"Invalid language: {key}."), loc="language"))
            if not parsed_language:
                errors.append(ErrorWrapper(Exception(f"Invalid language: {key}."), loc="language"))
            if isinstance(dictionary[key], int | str | None):
                result[key] = dictionary[key]
            else:
                errors.append(ErrorWrapper(Exception(f"Invalid content for language: {key}."), loc=("language","content")))

        if errors:
            raise ValidationError(
            errors,
            cls,
            )

        return cls(result)

Then use it in you schema/pydantic model like:

# products/pydantic.py
from pydantic import BaseModel
from validators.translated_field import Translatable

class BaseSchema(BaseModel):
    id: int

class CreateSchema(BaseSchema):
    name: Translatable
    ...your code

And use normal JSON field in SQLALchemy model!

# products/model.py
...
from sqlalchemy import Column, JSON
...
class Model(Base):
    name = Column(JSON, nullable=True)
    ...
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文