|
| 1 | +from __future__ import annotations |
| 2 | +from inspect import getfullargspec |
| 3 | +import json |
| 4 | +import pprint |
| 5 | +import re # noqa: F401 |
| 6 | +{{#vendorExtensions.x-py-other-imports}} |
| 7 | +{{{.}}} |
| 8 | +{{/vendorExtensions.x-py-other-imports}} |
| 9 | +{{#vendorExtensions.x-py-model-imports}} |
| 10 | +{{{.}}} |
| 11 | +{{/vendorExtensions.x-py-model-imports}} |
| 12 | +from typing import Union, Any, List, Set, TYPE_CHECKING, Optional, Dict |
| 13 | +from typing_extensions import Literal, Self |
| 14 | +from pydantic import Field |
| 15 | + |
| 16 | +{{#lambda.uppercase}}{{{classname}}}{{/lambda.uppercase}}_ANY_OF_SCHEMAS = [{{#anyOf}}"{{.}}"{{^-last}}, {{/-last}}{{/anyOf}}] |
| 17 | + |
| 18 | +class {{classname}}({{#parent}}{{{.}}}{{/parent}}{{^parent}}BaseModel{{/parent}}): |
| 19 | + """ |
| 20 | + {{{description}}}{{^description}}{{{classname}}}{{/description}} |
| 21 | + """ |
| 22 | + |
| 23 | +{{#composedSchemas.anyOf}} |
| 24 | + # data type: {{{dataType}}} |
| 25 | + {{vendorExtensions.x-py-name}}: {{{vendorExtensions.x-py-typing}}} |
| 26 | +{{/composedSchemas.anyOf}} |
| 27 | + if TYPE_CHECKING: |
| 28 | + actual_instance: Optional[Union[{{#anyOf}}{{{.}}}{{^-last}}, {{/-last}}{{/anyOf}}]] = None |
| 29 | + else: |
| 30 | + actual_instance: Any = None |
| 31 | + any_of_schemas: Set[str] = { {{#anyOf}}"{{.}}"{{^-last}}, {{/-last}}{{/anyOf}} } |
| 32 | + |
| 33 | + model_config = { |
| 34 | + "validate_assignment": True, |
| 35 | + "protected_namespaces": (), |
| 36 | + } |
| 37 | + |
| 38 | +{{#discriminator}} |
| 39 | +{{#propertyName}} |
| 40 | + # Discriminator's property name (OpenAPI v3) |
| 41 | + __openapi_discriminator_name__ = '{{{.}}}' |
| 42 | +{{/propertyName}} |
| 43 | + |
| 44 | +{{#mappedModels}} |
| 45 | + {{#-first}} |
| 46 | + # Discriminator's mapping (OpenAPI v3) |
| 47 | + __discriminator_value_class_map__ = { |
| 48 | + {{/-first}} |
| 49 | + '{{{mappingName}}}': '{{{modelName}}}'{{^-last}},{{/-last}} |
| 50 | + {{#-last}} |
| 51 | + } |
| 52 | + {{/-last}} |
| 53 | +{{/mappedModels}} |
| 54 | +{{/discriminator}} |
| 55 | + |
| 56 | + def __init__(self, *args, **kwargs) -> None: |
| 57 | + if args: |
| 58 | + if len(args) > 1: |
| 59 | + raise ValueError("If a position argument is used, only 1 is allowed to set `actual_instance`") |
| 60 | + if kwargs: |
| 61 | + raise ValueError("If a position argument is used, keyword arguments cannot be used.") |
| 62 | + super().__init__(actual_instance=args[0]) |
| 63 | + else: |
| 64 | + super().__init__(**kwargs) |
| 65 | + |
| 66 | + @field_validator('actual_instance') |
| 67 | + def actual_instance_must_validate_anyof(cls, v): |
| 68 | + {{#isNullable}} |
| 69 | + if v is None: |
| 70 | + return v |
| 71 | + |
| 72 | + {{/isNullable}} |
| 73 | + instance = {{{classname}}}.model_construct() |
| 74 | + error_messages = [] |
| 75 | + {{#composedSchemas.anyOf}} |
| 76 | + # validate data type: {{{dataType}}} |
| 77 | + {{#isContainer}} |
| 78 | + try: |
| 79 | + instance.{{vendorExtensions.x-py-name}} = v |
| 80 | + return v |
| 81 | + except (ValidationError, ValueError) as e: |
| 82 | + error_messages.append(str(e)) |
| 83 | + {{/isContainer}} |
| 84 | + {{^isContainer}} |
| 85 | + {{#isPrimitiveType}} |
| 86 | + try: |
| 87 | + instance.{{vendorExtensions.x-py-name}} = v |
| 88 | + return v |
| 89 | + except (ValidationError, ValueError) as e: |
| 90 | + error_messages.append(str(e)) |
| 91 | + {{/isPrimitiveType}} |
| 92 | + {{^isPrimitiveType}} |
| 93 | + if not isinstance(v, {{{dataType}}}): |
| 94 | + error_messages.append(f"Error! Input type `{type(v)}` is not `{{{dataType}}}`") |
| 95 | + else: |
| 96 | + return v |
| 97 | + |
| 98 | + {{/isPrimitiveType}} |
| 99 | + {{/isContainer}} |
| 100 | + {{/composedSchemas.anyOf}} |
| 101 | + if error_messages: |
| 102 | + # no match |
| 103 | + raise ValueError("No match found when setting the actual_instance in {{{classname}}} with anyOf schemas: {{#anyOf}}{{{.}}}{{^-last}}, {{/-last}}{{/anyOf}}. Details: " + ", ".join(error_messages)) |
| 104 | + else: |
| 105 | + return v |
| 106 | + |
| 107 | + @classmethod |
| 108 | + def from_dict(cls, obj: Dict[str, Any]) -> Self: |
| 109 | + return cls.from_json(json.dumps(obj)) |
| 110 | + |
| 111 | + @classmethod |
| 112 | + def from_json(cls, json_str: str) -> Self: |
| 113 | + """Returns the object represented by the json string""" |
| 114 | + instance = cls.model_construct() |
| 115 | + {{#isNullable}} |
| 116 | + if json_str is None: |
| 117 | + return instance |
| 118 | + |
| 119 | + {{/isNullable}} |
| 120 | + {{#discriminator}} |
| 121 | + |
| 122 | + # Try to deserialize using the discriminator |
| 123 | + json_obj = json.loads(json_str) |
| 124 | + discriminator_value = json_obj.get(cls.__openapi_discriminator_name__) |
| 125 | + |
| 126 | + if discriminator_value and discriminator_value in cls.__discriminator_value_class_map__: |
| 127 | + class_name = cls.__discriminator_value_class_map__[discriminator_value] |
| 128 | + target_class = globals()[class_name] |
| 129 | + try: |
| 130 | + instance.actual_instance = target_class.from_json(json_str) |
| 131 | + return instance |
| 132 | + except (ValidationError, ValueError) as e: |
| 133 | + raise ValueError(f"Failed to deserialize using discriminator '{discriminator_value}' -> {class_name}: {str(e)}") |
| 134 | + |
| 135 | + {{/discriminator}} |
| 136 | + error_messages = [] |
| 137 | + {{#composedSchemas.anyOf}} |
| 138 | + {{#isContainer}} |
| 139 | + # deserialize data into {{{dataType}}} |
| 140 | + try: |
| 141 | + # validation |
| 142 | + instance.{{vendorExtensions.x-py-name}} = json.loads(json_str) |
| 143 | + # assign value to actual_instance |
| 144 | + instance.actual_instance = instance.{{vendorExtensions.x-py-name}} |
| 145 | + return instance |
| 146 | + except (ValidationError, ValueError) as e: |
| 147 | + error_messages.append(str(e)) |
| 148 | + {{/isContainer}} |
| 149 | + {{^isContainer}} |
| 150 | + {{#isPrimitiveType}} |
| 151 | + # deserialize data into {{{dataType}}} |
| 152 | + try: |
| 153 | + # validation |
| 154 | + instance.{{vendorExtensions.x-py-name}} = json.loads(json_str) |
| 155 | + # assign value to actual_instance |
| 156 | + instance.actual_instance = instance.{{vendorExtensions.x-py-name}} |
| 157 | + return instance |
| 158 | + except (ValidationError, ValueError) as e: |
| 159 | + error_messages.append(str(e)) |
| 160 | + {{/isPrimitiveType}} |
| 161 | + {{^isPrimitiveType}} |
| 162 | + # {{vendorExtensions.x-py-name}}: {{{vendorExtensions.x-py-typing}}} |
| 163 | + try: |
| 164 | + instance.actual_instance = {{{dataType}}}.from_json(json_str) |
| 165 | + return instance |
| 166 | + except (ValidationError, ValueError) as e: |
| 167 | + error_messages.append(str(e)) |
| 168 | + {{/isPrimitiveType}} |
| 169 | + {{/isContainer}} |
| 170 | + {{/composedSchemas.anyOf}} |
| 171 | + |
| 172 | + if error_messages: |
| 173 | + # no match |
| 174 | + raise ValueError("No match found when deserializing the JSON string into {{{classname}}} with anyOf schemas: {{#anyOf}}{{{.}}}{{^-last}}, {{/-last}}{{/anyOf}}. Details: " + ", ".join(error_messages)) |
| 175 | + else: |
| 176 | + return instance |
| 177 | + |
| 178 | + def to_json(self) -> str: |
| 179 | + """Returns the JSON representation of the actual instance""" |
| 180 | + if self.actual_instance is None: |
| 181 | + return "null" |
| 182 | + |
| 183 | + if hasattr(self.actual_instance, "to_json") and callable(self.actual_instance.to_json): |
| 184 | + return self.actual_instance.to_json() |
| 185 | + else: |
| 186 | + return json.dumps(self.actual_instance) |
| 187 | + |
| 188 | + def to_dict(self) -> Optional[Union[Dict[str, Any], {{#anyOf}}{{.}}{{^-last}}, {{/-last}}{{/anyOf}}]]: |
| 189 | + """Returns the dict representation of the actual instance""" |
| 190 | + if self.actual_instance is None: |
| 191 | + return None |
| 192 | + |
| 193 | + if hasattr(self.actual_instance, "to_dict") and callable(self.actual_instance.to_dict): |
| 194 | + return self.actual_instance.to_dict() |
| 195 | + else: |
| 196 | + return self.actual_instance |
| 197 | + |
| 198 | + def to_str(self) -> str: |
| 199 | + """Returns the string representation of the actual instance""" |
| 200 | + return pprint.pformat(self.model_dump()) |
| 201 | + |
| 202 | +{{#vendorExtensions.x-py-postponed-model-imports.size}} |
| 203 | +{{#vendorExtensions.x-py-postponed-model-imports}} |
| 204 | +{{{.}}} |
| 205 | +{{/vendorExtensions.x-py-postponed-model-imports}} |
| 206 | +# TODO: Rewrite to not use raise_errors |
| 207 | +{{classname}}.model_rebuild(raise_errors=False) |
| 208 | +{{/vendorExtensions.x-py-postponed-model-imports.size}} |
0 commit comments