-
-
Notifications
You must be signed in to change notification settings - Fork 60
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
feat: add pydantic v2 support. Closes #415
- Loading branch information
1 parent
0b88f4b
commit 36c0db3
Showing
36 changed files
with
2,765 additions
and
433 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,6 @@ | ||
from .main import AvroBaseModel # noqa: F401 I001 | ||
from .mapper import PYDANTIC_INMUTABLE_FIELDS_CLASSES, PYDANTIC_LOGICAL_TYPES_FIELDS_CLASSES | ||
from dataclasses_avroschema.fields import mapper | ||
|
||
mapper.IMMUTABLE_FIELDS_CLASSES.update(PYDANTIC_INMUTABLE_FIELDS_CLASSES) | ||
mapper.LOGICAL_TYPES_FIELDS_CLASSES.update(PYDANTIC_LOGICAL_TYPES_FIELDS_CLASSES) # type: ignore |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,99 @@ | ||
from typing import Any, Callable, Optional, Type, TypeVar | ||
|
||
from fastavro.validation import validate | ||
|
||
from dataclasses_avroschema import serialization | ||
from dataclasses_avroschema.schema_generator import AVRO, AvroModel | ||
from dataclasses_avroschema.types import JsonDict | ||
from dataclasses_avroschema.utils import standardize_custom_type | ||
|
||
from .parser import PydanticV1Parser | ||
|
||
try: | ||
from pydantic.v1 import BaseModel # pragma: no cover | ||
except ImportError as ex: # pragma: no cover | ||
raise Exception("pydantic must be installed in order to use AvroBaseModel") from ex # pragma: no cover | ||
|
||
CT = TypeVar("CT", bound="AvroBaseModel") | ||
|
||
|
||
class AvroBaseModel(BaseModel, AvroModel): # type: ignore | ||
@classmethod | ||
def generate_dataclass(cls: Type[CT]) -> Type[CT]: | ||
return cls | ||
|
||
@classmethod | ||
def json_schema(cls: Type[CT], *args: Any, **kwargs: Any) -> str: | ||
return cls.schema_json(*args, **kwargs) | ||
|
||
@classmethod | ||
def standardize_type(cls: Type[CT], data: dict) -> Any: | ||
""" | ||
Standardization factory that converts data according to the | ||
user-defined pydantic json_encoders prior to passing values | ||
to the standard type conversion factory | ||
""" | ||
encoders = cls.__config__.json_encoders | ||
for k, v in data.items(): | ||
v_type = type(v) | ||
if v_type in encoders: | ||
encode_method = encoders[v_type] | ||
data[k] = encode_method(v) | ||
elif isinstance(v, dict): | ||
cls.standardize_type(v) | ||
|
||
return standardize_custom_type(data) | ||
|
||
def asdict(self, standardize_factory: Optional[Callable[..., Any]] = None) -> JsonDict: | ||
""" | ||
Returns this model in dictionary form. This method differs from | ||
pydantic's dict by converting all values to their Avro representation. | ||
It also doesn't provide the exclude, include, by_alias, etc. | ||
parameters that dict provides. | ||
""" | ||
data = dict(self) | ||
|
||
standardize_method = standardize_factory or self.standardize_type | ||
|
||
# the standardize called can be replaced if we have a custom implementation of asdict | ||
# for now I think is better to use the native implementation | ||
return standardize_method(data) | ||
|
||
def serialize(self, serialization_type: str = AVRO) -> bytes: | ||
""" | ||
Overrides the base AvroModel's serialize method to inject this | ||
class's standardization factory method | ||
""" | ||
schema = self.avro_schema_to_python() | ||
|
||
return serialization.serialize( | ||
self.asdict(standardize_factory=self.standardize_type), | ||
schema, | ||
serialization_type=serialization_type, | ||
) | ||
|
||
def validate_avro(self) -> bool: | ||
""" | ||
Validate that instance matches the avro schema | ||
""" | ||
schema = self.avro_schema_to_python() | ||
return validate(self.asdict(), schema) | ||
|
||
@classmethod | ||
def fake(cls: Type[CT], **data: Any) -> CT: | ||
""" | ||
Creates a fake instance of the model. | ||
Attributes: | ||
data: Dict[str, Any] represent the user values to use in the instance | ||
""" | ||
# only generate fakes for fields that were not provided in data | ||
payload = {field.name: field.fake() for field in cls.get_fields() if field.name not in data.keys()} | ||
payload.update(data) | ||
|
||
return cls.parse_obj(payload) | ||
|
||
@classmethod | ||
def _generate_parser(cls: Type[CT]) -> PydanticV1Parser: | ||
cls._metadata = cls.generate_metadata() | ||
return PydanticV1Parser(type=cls._klass, metadata=cls._metadata, parent=cls._parent or cls) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,40 @@ | ||
from pydantic import v1 | ||
|
||
from dataclasses_avroschema.pydantic import fields | ||
|
||
PYDANTIC_INMUTABLE_FIELDS_CLASSES = { | ||
v1.FilePath: fields.FilePathField, | ||
v1.DirectoryPath: fields.DirectoryPathField, | ||
v1.EmailStr: fields.EmailStrField, | ||
v1.NameEmail: fields.NameEmailField, | ||
v1.AnyUrl: fields.AnyUrlField, | ||
v1.AnyHttpUrl: fields.AnyHttpUrlField, | ||
v1.HttpUrl: fields.HttpUrlField, | ||
v1.FileUrl: fields.FileUrlField, | ||
v1.PostgresDsn: fields.PostgresDsnField, | ||
v1.CockroachDsn: fields.CockroachDsnField, | ||
v1.AmqpDsn: fields.AmqpDsnField, | ||
v1.RedisDsn: fields.RedisDsnField, | ||
v1.MongoDsn: fields.MongoDsnField, | ||
v1.KafkaDsn: fields.KafkaDsnField, | ||
v1.SecretStr: fields.SecretStrField, | ||
v1.IPvAnyAddress: fields.IPvAnyAddressField, | ||
v1.IPvAnyInterface: fields.IPvAnyInterfaceField, | ||
v1.IPvAnyNetwork: fields.IPvAnyNetworkField, | ||
v1.NegativeFloat: fields.NegativeFloatField, | ||
v1.PositiveFloat: fields.PositiveFloatField, | ||
v1.NegativeInt: fields.NegativeIntField, | ||
v1.PositiveInt: fields.PositiveIntField, | ||
v1.ConstrainedInt: fields.ConstrainedIntField, | ||
# ConstrainedIntValue is a dynamic type that needs to be referenced by qualified name | ||
# and cannot be imported directly | ||
"ConstrainedIntValue": fields.ConstrainedIntField, | ||
} | ||
|
||
|
||
PYDANTIC_LOGICAL_TYPES_FIELDS_CLASSES = { | ||
v1.UUID1: fields.UUID1Field, | ||
v1.UUID3: fields.UUID3Field, | ||
v1.UUID4: fields.UUID4Field, | ||
v1.UUID5: fields.UUID5Field, | ||
} |
Oops, something went wrong.