Skip to content

Commit

Permalink
fix: model generator refactored (#569)
Browse files Browse the repository at this point in the history
  • Loading branch information
marcosschroh authored Mar 11, 2024
1 parent a5fa3c1 commit c9c31e8
Show file tree
Hide file tree
Showing 18 changed files with 826 additions and 674 deletions.
2 changes: 1 addition & 1 deletion dataclasses_avroschema/__init__.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
from .schema_generator import AvroModel # noqa: F401 I001
from .types import * # noqa: F401 F403
from .model_generator.generator import BaseClassEnum, ModelGenerator # noqa: F401
from .model_generator.generator import BaseClassEnum, ModelType, ModelGenerator # noqa: F401
from .fields.field_utils import * # noqa: F401 F403
from .fields.fields import * # noqa: F401 F403
7 changes: 0 additions & 7 deletions dataclasses_avroschema/model_generator/base_class.py

This file was deleted.

668 changes: 57 additions & 611 deletions dataclasses_avroschema/model_generator/generator.py

Large diffs are not rendered by default.

Empty file.
Empty file.
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
import typing
from dataclasses import dataclass

from dataclasses_avroschema.model_generator.lang.python import templates
from dataclasses_avroschema.model_generator.lang.python.base import BaseGenerator
from dataclasses_avroschema.types import JsonDict


@dataclass
class AvroDanticModelGenerator(BaseGenerator):
def __post_init__(self) -> None:
super().__post_init__()

self.base_class = "AvroBaseModel"
self.imports.add("from dataclasses_avroschema.pydantic import AvroBaseModel")
self.imports_dict = {
"dataclass_field": "from pydantic import Field",
}

# Templates
self.field_template = templates.pydantic_field_template

def _resolve_type_from_metadata(self, *, field: JsonDict) -> typing.Optional[str]:
"""
Check if the language type must be replaced with any extra class which
was specified in the field metadata. This method should be only called
after the native type was resolved properly.
An example of this if when a pydantic field was used in the model:
class MyModel(AvroBaseModel):
email: pydantic.EmailStr
then the email field is represented as:
{"name": "email", "type": {"type": "string", "pydantic-class": "EmailStr"}}
For now we only recognize the attribute `pydantic-class` but in the future
new way might be added, for example: `java-class`.
"""
pydantic_class = field.get("pydantic-class")

if pydantic_class is not None:
self.imports.add("import pydantic")
return f"pydantic.{pydantic_class}"
return None

def render_dataclass_field(self, properties: str) -> str:
self.imports.add("from pydantic import Field")
return super().render_dataclass_field(properties=properties)
Loading

0 comments on commit c9c31e8

Please sign in to comment.