All Downloads are FREE. Search and download functionalities are using the official Maven repository.

python-pydantic-v1.model_generic.mustache Maven / Gradle / Ivy

There is a newer version: 7.9.0
Show newest version
from __future__ import annotations
import pprint
import re  # noqa: F401
import json

{{#vendorExtensions.x-py-datetime-imports}}{{#-first}}from datetime import{{/-first}} {{{.}}}{{^-last}},{{/-last}}{{/vendorExtensions.x-py-datetime-imports}}
{{#vendorExtensions.x-py-typing-imports}}{{#-first}}from typing import{{/-first}} {{{.}}}{{^-last}},{{/-last}}{{/vendorExtensions.x-py-typing-imports}}
{{#vendorExtensions.x-py-pydantic-imports}}{{#-first}}from pydantic import{{/-first}} {{{.}}}{{^-last}},{{/-last}}{{/vendorExtensions.x-py-pydantic-imports}}
{{#vendorExtensions.x-py-model-imports}}
{{{.}}}
{{/vendorExtensions.x-py-model-imports}}

class {{classname}}({{#parent}}{{{.}}}{{/parent}}{{^parent}}BaseModel{{/parent}}):
    """
    {{#description}}{{{description}}}  # noqa: E501{{/description}}{{^description}}{{{classname}}}{{/description}}
    """
{{#vars}}
    {{name}}: {{{vendorExtensions.x-py-typing}}}
{{/vars}}
{{#isAdditionalPropertiesTrue}}
    additional_properties: Dict[str, Any] = {}
{{/isAdditionalPropertiesTrue}}
    __properties = [{{#allVars}}"{{baseName}}"{{^-last}}, {{/-last}}{{/allVars}}]
{{#vars}}
    {{#vendorExtensions.x-regex}}

    @validator('{{{name}}}')
    def {{{name}}}_validate_regular_expression(cls, value):
        """Validates the regular expression"""
        {{^required}}
        if value is None:
            return value

        {{/required}}
        {{#required}}
        {{#isNullable}}
        if value is None:
            return value

        {{/isNullable}}
        {{/required}}
        if not re.match(r"{{{.}}}", value{{#vendorExtensions.x-modifiers}} ,re.{{{.}}}{{/vendorExtensions.x-modifiers}}):
            raise ValueError(r"must validate the regular expression {{{vendorExtensions.x-pattern}}}")
        return value
    {{/vendorExtensions.x-regex}}
    {{#isEnum}}

    @validator('{{{name}}}')
    def {{{name}}}_validate_enum(cls, value):
        """Validates the enum"""
        {{^required}}
        if value is None:
            return value

        {{/required}}
        {{#required}}
        {{#isNullable}}
        if value is None:
            return value

        {{/isNullable}}
        {{/required}}
        {{#isArray}}
        for i in value:
            if i not in ({{#allowableValues}}{{#enumVars}}{{{value}}}{{^-last}}, {{/-last}}{{/enumVars}}{{/allowableValues}}):
                raise ValueError("each list item must be one of ({{#allowableValues}}{{#enumVars}}{{{value}}}{{^-last}}, {{/-last}}{{/enumVars}}{{/allowableValues}})")
        {{/isArray}}
        {{^isArray}}
        if value not in ({{#allowableValues}}{{#enumVars}}{{{value}}}{{^-last}}, {{/-last}}{{/enumVars}}{{/allowableValues}}):
            raise ValueError("must be one of enum values ({{#allowableValues}}{{#enumVars}}{{{value}}}{{^-last}}, {{/-last}}{{/enumVars}}{{/allowableValues}})")
        {{/isArray}}
        return value
    {{/isEnum}}
{{/vars}}

    class Config:
        """Pydantic configuration"""
        allow_population_by_field_name = True
        validate_assignment = True

{{#hasChildren}}
{{#discriminator}}
    # JSON field name that stores the object type
    __discriminator_property_name = '{{discriminator.propertyBaseName}}'

    {{#mappedModels}}
    {{#-first}}
    # discriminator mappings
    __discriminator_value_class_map = {
    {{/-first}}
        '{{{mappingName}}}': '{{{modelName}}}'{{^-last}},{{/-last}}
    {{#-last}}
    }

    @classmethod
    def get_discriminator_value(cls, obj: dict) -> str:
        """Returns the discriminator value (object type) of the data"""
        discriminator_value = obj[cls.__discriminator_property_name]
        if discriminator_value:
            return cls.__discriminator_value_class_map.get(discriminator_value)
        else:
            return None
    {{/-last}}
    {{/mappedModels}}

{{/discriminator}}
{{/hasChildren}}
    def to_str(self) -> str:
        """Returns the string representation of the model using alias"""
        return pprint.pformat(self.dict(by_alias=True))

    def to_json(self) -> str:
        """Returns the JSON representation of the model using alias"""
        return json.dumps(self.to_dict())

    @classmethod
    def from_json(cls, json_str: str) -> {{^hasChildren}}{{{classname}}}{{/hasChildren}}{{#hasChildren}}{{#discriminator}}Union({{#children}}{{{classname}}}{{^-last}}, {{/-last}}{{/children}}){{/discriminator}}{{^discriminator}}{{{classname}}}{{/discriminator}}{{/hasChildren}}:
        """Create an instance of {{{classname}}} from a JSON string"""
        return cls.from_dict(json.loads(json_str))

    def to_dict(self):
        """Returns the dictionary representation of the model using alias"""
        _dict = self.dict(by_alias=True,
                          exclude={
                            {{#vendorExtensions.x-py-readonly}}
                            "{{{.}}}",
                            {{/vendorExtensions.x-py-readonly}}
                            {{#isAdditionalPropertiesTrue}}
                            "additional_properties"
                            {{/isAdditionalPropertiesTrue}}
                          },
                          exclude_none=True)
        {{#allVars}}
        {{#isContainer}}
        {{#isArray}}
        {{#items.isArray}}
        {{^items.items.isPrimitiveType}}
        # override the default output from pydantic by calling `to_dict()` of each item in {{{name}}} (list of list)
        _items = []
        if self.{{{name}}}:
            for _item in self.{{{name}}}:
                if _item:
                    _items.append(
                         [_inner_item.to_dict() for _inner_item in _item if _inner_item is not None]
                    )
            _dict['{{{baseName}}}'] = _items
        {{/items.items.isPrimitiveType}}
        {{/items.isArray}}
        {{^items.isArray}}
        {{^items.isPrimitiveType}}
        {{^items.isEnumOrRef}}
        # override the default output from pydantic by calling `to_dict()` of each item in {{{name}}} (list)
        _items = []
        if self.{{{name}}}:
            for _item in self.{{{name}}}:
                if _item:
                    _items.append(_item.to_dict())
            _dict['{{{baseName}}}'] = _items
        {{/items.isEnumOrRef}}
        {{/items.isPrimitiveType}}
        {{/items.isArray}}
        {{/isArray}}
        {{#isMap}}
        {{#items.isArray}}
        # override the default output from pydantic by calling `to_dict()` of each value in {{{name}}} (dict of array)
        _field_dict_of_array = {}
        if self.{{{name}}}:
            for _key in self.{{{name}}}:
                if self.{{{name}}}[_key]:
                    _field_dict_of_array[_key] = [
                        _item.to_dict() for _item in self.{{{name}}}[_key]
                    ]
            _dict['{{{baseName}}}'] = _field_dict_of_array
        {{/items.isArray}}
        {{^items.isArray}}
        {{^items.isPrimitiveType}}
        {{^items.isEnumOrRef}}
        # override the default output from pydantic by calling `to_dict()` of each value in {{{name}}} (dict)
        _field_dict = {}
        if self.{{{name}}}:
            for _key in self.{{{name}}}:
                if self.{{{name}}}[_key]:
                    _field_dict[_key] = self.{{{name}}}[_key].to_dict()
            _dict['{{{baseName}}}'] = _field_dict
        {{/items.isEnumOrRef}}
        {{/items.isPrimitiveType}}
        {{/items.isArray}}
        {{/isMap}}
        {{/isContainer}}
        {{^isContainer}}
        {{^isPrimitiveType}}
        {{^isEnumOrRef}}
        # override the default output from pydantic by calling `to_dict()` of {{{name}}}
        if self.{{{name}}}:
            _dict['{{{baseName}}}'] = self.{{{name}}}.to_dict()
        {{/isEnumOrRef}}
        {{/isPrimitiveType}}
        {{/isContainer}}
        {{/allVars}}
        {{#isAdditionalPropertiesTrue}}
        # puts key-value pairs in additional_properties in the top level
        if self.additional_properties is not None:
            for _key, _value in self.additional_properties.items():
                _dict[_key] = _value

        {{/isAdditionalPropertiesTrue}}
        {{#allVars}}
        {{#isNullable}}
        # set to None if {{{name}}} (nullable) is None
        # and __fields_set__ contains the field
        if self.{{name}} is None and "{{{name}}}" in self.__fields_set__:
            _dict['{{{baseName}}}'] = None

        {{/isNullable}}
        {{/allVars}}
        return _dict

    @classmethod
    def from_dict(cls, obj: dict) -> {{^hasChildren}}{{{classname}}}{{/hasChildren}}{{#hasChildren}}{{#discriminator}}Union({{#children}}{{{classname}}}{{^-last}}, {{/-last}}{{/children}}){{/discriminator}}{{^discriminator}}{{{classname}}}{{/discriminator}}{{/hasChildren}}:
        """Create an instance of {{{classname}}} from a dict"""
        {{#hasChildren}}
        {{#discriminator}}
        # look up the object type based on discriminator mapping
        object_type = cls.get_discriminator_value(obj)
        if object_type:
            klass = globals()[object_type]
            return klass.from_dict(obj)
        else:
            raise ValueError("{{{classname}}} failed to lookup discriminator value from " +
                             json.dumps(obj) + ". Discriminator property name: " + cls.__discriminator_property_name +
                             ", mapping: " + json.dumps(cls.__discriminator_value_class_map))
        {{/discriminator}}
        {{/hasChildren}}
        {{^hasChildren}}
        if obj is None:
            return None

        if not isinstance(obj, dict):
            return {{{classname}}}.parse_obj(obj)

        {{#disallowAdditionalPropertiesIfNotPresent}}
        {{^isAdditionalPropertiesTrue}}
        # raise errors for additional fields in the input
        for _key in obj.keys():
            if _key not in cls.__properties:
                raise ValueError("Error due to additional fields (not defined in {{classname}}) in the input: " + obj)

        {{/isAdditionalPropertiesTrue}}
        {{/disallowAdditionalPropertiesIfNotPresent}}
        _obj = {{{classname}}}.parse_obj({
            {{#allVars}}
            {{#isContainer}}
            {{#isArray}}
            {{#items.isArray}}
            {{#items.items.isPrimitiveType}}
            "{{{name}}}": obj.get("{{{baseName}}}"){{^-last}},{{/-last}}
            {{/items.items.isPrimitiveType}}
            {{^items.items.isPrimitiveType}}
            "{{{name}}}": [
                    [{{{items.items.dataType}}}.from_dict(_inner_item) for _inner_item in _item]
                    for _item in obj.get("{{{baseName}}}")
                ] if obj.get("{{{baseName}}}") is not None else None{{^-last}},{{/-last}}
            {{/items.items.isPrimitiveType}}
            {{/items.isArray}}
            {{^items.isArray}}
            {{^items.isPrimitiveType}}
            {{#items.isEnumOrRef}}
            "{{{name}}}": obj.get("{{{baseName}}}"){{^-last}},{{/-last}}
            {{/items.isEnumOrRef}}
            {{^items.isEnumOrRef}}
            "{{{name}}}": [{{{items.dataType}}}.from_dict(_item) for _item in obj.get("{{{baseName}}}")] if obj.get("{{{baseName}}}") is not None else None{{^-last}},{{/-last}}
            {{/items.isEnumOrRef}}
            {{/items.isPrimitiveType}}
            {{#items.isPrimitiveType}}
            "{{{name}}}": obj.get("{{{baseName}}}"){{^-last}},{{/-last}}
            {{/items.isPrimitiveType}}
            {{/items.isArray}}
            {{/isArray}}
            {{#isMap}}
            {{^items.isPrimitiveType}}
            {{^items.isEnumOrRef}}
            {{#items.isContainer}}
            {{#items.isMap}}
            "{{{name}}}": dict(
                (_k, dict(
                    (_ik, {{{items.items.dataType}}}.from_dict(_iv))
                        for _ik, _iv in _v.items()
                    )
                    if _v is not None
                    else None
                )
                for _k, _v in obj.get("{{{baseName}}}").items()
            )
            if obj.get("{{{baseName}}}") is not None
            else None{{^-last}},{{/-last}}
            {{/items.isMap}}
            {{#items.isArray}}
            "{{{name}}}": dict(
                (_k,
                        [{{{items.items.dataType}}}.from_dict(_item) for _item in _v]
                        if _v is not None
                        else None
                )
                for _k, _v in obj.get("{{{baseName}}}").items()
            ){{^-last}},{{/-last}}
            {{/items.isArray}}
            {{/items.isContainer}}
            {{^items.isContainer}}
            "{{{name}}}": dict(
                (_k, {{{items.dataType}}}.from_dict(_v))
                for _k, _v in obj.get("{{{baseName}}}").items()
            )
            if obj.get("{{{baseName}}}") is not None
            else None{{^-last}},{{/-last}}
            {{/items.isContainer}}
            {{/items.isEnumOrRef}}
            {{#items.isEnumOrRef}}
            "{{{name}}}": dict((_k, _v) for _k, _v in obj.get("{{{baseName}}}").items()){{^-last}},{{/-last}}
            {{/items.isEnumOrRef}}
            {{/items.isPrimitiveType}}
            {{#items.isPrimitiveType}}
            "{{{name}}}": obj.get("{{{baseName}}}"){{^-last}},{{/-last}}
            {{/items.isPrimitiveType}}
            {{/isMap}}
            {{/isContainer}}
            {{^isContainer}}
            {{^isPrimitiveType}}
            {{^isEnumOrRef}}
            "{{{name}}}": {{{dataType}}}.from_dict(obj.get("{{{baseName}}}")) if obj.get("{{{baseName}}}") is not None else None{{^-last}},{{/-last}}
            {{/isEnumOrRef}}
            {{#isEnumOrRef}}
            "{{{name}}}": obj.get("{{{baseName}}}"){{^-last}},{{/-last}}
            {{/isEnumOrRef}}
            {{/isPrimitiveType}}
            {{#isPrimitiveType}}
            {{#defaultValue}}
            "{{{name}}}": obj.get("{{{baseName}}}") if obj.get("{{{baseName}}}") is not None else {{{defaultValue}}}{{^-last}},{{/-last}}
            {{/defaultValue}}
            {{^defaultValue}}
            "{{{name}}}": obj.get("{{{baseName}}}"){{^-last}},{{/-last}}
            {{/defaultValue}}
            {{/isPrimitiveType}}
            {{/isContainer}}
            {{/allVars}}
        })
        {{#isAdditionalPropertiesTrue}}
        # store additional fields in additional_properties
        for _key in obj.keys():
            if _key not in cls.__properties:
                _obj.additional_properties[_key] = obj.get(_key)

        {{/isAdditionalPropertiesTrue}}
        return _obj
        {{/hasChildren}}

{{#vendorExtensions.x-py-postponed-model-imports.size}}
{{#vendorExtensions.x-py-postponed-model-imports}}
{{{.}}}
{{/vendorExtensions.x-py-postponed-model-imports}}
{{classname}}.update_forward_refs()
{{/vendorExtensions.x-py-postponed-model-imports.size}}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy