[python-nextgen] Fix dict of dict of object in python-nextgen (#15239)

* fix dict of dict of object in python nextgen

* update samples
This commit is contained in:
William Cheng 2023-04-18 14:59:08 +08:00 committed by GitHub
parent 1881100742
commit f5b4490bc9
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
21 changed files with 433 additions and 5 deletions

View File

@ -241,7 +241,42 @@ class {{classname}}({{#parent}}{{{.}}}{{/parent}}{{^parent}}BaseModel{{/parent}}
{{#isMap}}
{{^items.isPrimitiveType}}
{{^items.isEnumOrRef}}
"{{{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.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, [(_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.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}}

View File

@ -2147,3 +2147,12 @@ components:
type: string
circular_ref:
$ref: '#/components/schemas/Circular-Reference-Model'
InnerDictWithAdditionalProperties:
type: object
additionalProperties:
$ref: "#/components/schemas/InnerDictWithProperty"
Parent:
type: object
properties:
optionalDict:
$ref: "#/components/schemas/DictWithAdditionalProperties"

View File

@ -58,6 +58,7 @@ docs/OuterEnumDefaultValue.md
docs/OuterEnumInteger.md
docs/OuterEnumIntegerDefaultValue.md
docs/OuterObjectWithEnumProperty.md
docs/Parent.md
docs/ParentWithOptionalDict.md
docs/Pet.md
docs/PetApi.md
@ -139,6 +140,7 @@ petstore_api/models/outer_enum_default_value.py
petstore_api/models/outer_enum_integer.py
petstore_api/models/outer_enum_integer_default_value.py
petstore_api/models/outer_object_with_enum_property.py
petstore_api/models/parent.py
petstore_api/models/parent_with_optional_dict.py
petstore_api/models/pet.py
petstore_api/models/pig.py

View File

@ -183,6 +183,7 @@ Class | Method | HTTP request | Description
- [OuterEnumInteger](docs/OuterEnumInteger.md)
- [OuterEnumIntegerDefaultValue](docs/OuterEnumIntegerDefaultValue.md)
- [OuterObjectWithEnumProperty](docs/OuterObjectWithEnumProperty.md)
- [Parent](docs/Parent.md)
- [ParentWithOptionalDict](docs/ParentWithOptionalDict.md)
- [Pet](docs/Pet.md)
- [Pig](docs/Pig.md)

View File

@ -0,0 +1,28 @@
# Parent
## Properties
Name | Type | Description | Notes
------------ | ------------- | ------------- | -------------
**optional_dict** | [**Dict[str, InnerDictWithProperty]**](InnerDictWithProperty.md) | | [optional]
## Example
```python
from petstore_api.models.parent import Parent
# TODO update the JSON string below
json = "{}"
# create an instance of Parent from a JSON string
parent_instance = Parent.from_json(json)
# print the JSON string representation of the object
print Parent.to_json()
# convert the object into a dict
parent_dict = parent_instance.to_dict()
# create an instance of Parent from a dict
parent_form_dict = parent.from_dict(parent_dict)
```
[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md)

View File

@ -86,6 +86,7 @@ from petstore_api.models.outer_enum_default_value import OuterEnumDefaultValue
from petstore_api.models.outer_enum_integer import OuterEnumInteger
from petstore_api.models.outer_enum_integer_default_value import OuterEnumIntegerDefaultValue
from petstore_api.models.outer_object_with_enum_property import OuterObjectWithEnumProperty
from petstore_api.models.parent import Parent
from petstore_api.models.parent_with_optional_dict import ParentWithOptionalDict
from petstore_api.models.pet import Pet
from petstore_api.models.pig import Pig

View File

@ -65,6 +65,7 @@ from petstore_api.models.outer_enum_default_value import OuterEnumDefaultValue
from petstore_api.models.outer_enum_integer import OuterEnumInteger
from petstore_api.models.outer_enum_integer_default_value import OuterEnumIntegerDefaultValue
from petstore_api.models.outer_object_with_enum_property import OuterObjectWithEnumProperty
from petstore_api.models.parent import Parent
from petstore_api.models.parent_with_optional_dict import ParentWithOptionalDict
from petstore_api.models.pet import Pet
from petstore_api.models.pig import Pig

View File

@ -76,7 +76,12 @@ class MixedPropertiesAndAdditionalPropertiesClass(BaseModel):
_obj = MixedPropertiesAndAdditionalPropertiesClass.parse_obj({
"uuid": obj.get("uuid"),
"date_time": obj.get("dateTime"),
"map": dict((_k, Animal.from_dict(_v)) for _k, _v in obj.get("map").items()) if obj.get("map") is not None else None
"map": dict(
(_k, Animal.from_dict(_v))
for _k, _v in obj.get("map").items()
)
if obj.get("map") is not None
else None
})
return _obj

View File

@ -0,0 +1,83 @@
# coding: utf-8
"""
OpenAPI Petstore
This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501
The version of the OpenAPI document: 1.0.0
Generated by OpenAPI Generator (https://openapi-generator.tech)
Do not edit the class manually.
"""
from __future__ import annotations
from inspect import getfullargspec
import pprint
import re # noqa: F401
import json
from typing import Dict, Optional
from pydantic import BaseModel, Field
from petstore_api.models.inner_dict_with_property import InnerDictWithProperty
class Parent(BaseModel):
"""
Parent
"""
optional_dict: Optional[Dict[str, InnerDictWithProperty]] = Field(None, alias="optionalDict")
__properties = ["optionalDict"]
class Config:
allow_population_by_field_name = True
validate_assignment = True
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) -> Parent:
"""Create an instance of Parent 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={
},
exclude_none=True)
# override the default output from pydantic by calling `to_dict()` of each value in optional_dict (dict)
_field_dict = {}
if self.optional_dict:
for _key in self.optional_dict:
if self.optional_dict[_key]:
_field_dict[_key] = self.optional_dict[_key].to_dict()
_dict['optionalDict'] = _field_dict
return _dict
@classmethod
def from_dict(cls, obj: dict) -> Parent:
"""Create an instance of Parent from a dict"""
if obj is None:
return None
if type(obj) is not dict:
return Parent.parse_obj(obj)
_obj = Parent.parse_obj({
"optional_dict": dict(
(_k, InnerDictWithProperty.from_dict(_v))
for _k, _v in obj.get("optionalDict").items()
)
if obj.get("optionalDict") is not None
else None
})
return _obj

View File

@ -72,7 +72,12 @@ class ParentWithOptionalDict(BaseModel):
return ParentWithOptionalDict.parse_obj(obj)
_obj = ParentWithOptionalDict.parse_obj({
"optional_dict": dict((_k, InnerDictWithProperty.from_dict(_v)) for _k, _v in obj.get("optionalDict").items()) if obj.get("optionalDict") is not None else None
"optional_dict": dict(
(_k, InnerDictWithProperty.from_dict(_v))
for _k, _v in obj.get("optionalDict").items()
)
if obj.get("optionalDict") is not None
else None
})
return _obj

View File

@ -0,0 +1,57 @@
# coding: utf-8
"""
OpenAPI Petstore
This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501
The version of the OpenAPI document: 1.0.0
Generated by OpenAPI Generator (https://openapi-generator.tech)
Do not edit the class manually.
"""
import unittest
import datetime
import petstore_api
from petstore_api.models.parent import Parent # noqa: E501
from petstore_api.rest import ApiException
class TestParent(unittest.TestCase):
"""Parent unit test stubs"""
def setUp(self):
pass
def tearDown(self):
pass
def make_instance(self, include_optional):
"""Test Parent
include_option is a boolean, when False only required
params are included, when True both required and
optional params are included """
# uncomment below to create an instance of `Parent`
"""
model = petstore_api.models.parent.Parent() # noqa: E501
if include_optional :
return Parent(
optional_dict = {
'key' : petstore_api.models.inner_dict_with_property.InnerDictWithProperty(
a_property = petstore_api.models.a_property.aProperty(), )
}
)
else :
return Parent(
)
"""
def testParent(self):
"""Test Parent"""
# inst_req_only = self.make_instance(include_optional=False)
# inst_req_and_optional = self.make_instance(include_optional=True)
if __name__ == '__main__':
unittest.main()

View File

@ -58,6 +58,7 @@ docs/OuterEnumDefaultValue.md
docs/OuterEnumInteger.md
docs/OuterEnumIntegerDefaultValue.md
docs/OuterObjectWithEnumProperty.md
docs/Parent.md
docs/ParentWithOptionalDict.md
docs/Pet.md
docs/PetApi.md
@ -139,6 +140,7 @@ petstore_api/models/outer_enum_default_value.py
petstore_api/models/outer_enum_integer.py
petstore_api/models/outer_enum_integer_default_value.py
petstore_api/models/outer_object_with_enum_property.py
petstore_api/models/parent.py
petstore_api/models/parent_with_optional_dict.py
petstore_api/models/pet.py
petstore_api/models/pig.py

View File

@ -183,6 +183,7 @@ Class | Method | HTTP request | Description
- [OuterEnumInteger](docs/OuterEnumInteger.md)
- [OuterEnumIntegerDefaultValue](docs/OuterEnumIntegerDefaultValue.md)
- [OuterObjectWithEnumProperty](docs/OuterObjectWithEnumProperty.md)
- [Parent](docs/Parent.md)
- [ParentWithOptionalDict](docs/ParentWithOptionalDict.md)
- [Pet](docs/Pet.md)
- [Pig](docs/Pig.md)

View File

@ -0,0 +1,28 @@
# Parent
## Properties
Name | Type | Description | Notes
------------ | ------------- | ------------- | -------------
**optional_dict** | [**Dict[str, InnerDictWithProperty]**](InnerDictWithProperty.md) | | [optional]
## Example
```python
from petstore_api.models.parent import Parent
# TODO update the JSON string below
json = "{}"
# create an instance of Parent from a JSON string
parent_instance = Parent.from_json(json)
# print the JSON string representation of the object
print Parent.to_json()
# convert the object into a dict
parent_dict = parent_instance.to_dict()
# create an instance of Parent from a dict
parent_form_dict = parent.from_dict(parent_dict)
```
[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md)

View File

@ -86,6 +86,7 @@ from petstore_api.models.outer_enum_default_value import OuterEnumDefaultValue
from petstore_api.models.outer_enum_integer import OuterEnumInteger
from petstore_api.models.outer_enum_integer_default_value import OuterEnumIntegerDefaultValue
from petstore_api.models.outer_object_with_enum_property import OuterObjectWithEnumProperty
from petstore_api.models.parent import Parent
from petstore_api.models.parent_with_optional_dict import ParentWithOptionalDict
from petstore_api.models.pet import Pet
from petstore_api.models.pig import Pig

View File

@ -65,6 +65,7 @@ from petstore_api.models.outer_enum_default_value import OuterEnumDefaultValue
from petstore_api.models.outer_enum_integer import OuterEnumInteger
from petstore_api.models.outer_enum_integer_default_value import OuterEnumIntegerDefaultValue
from petstore_api.models.outer_object_with_enum_property import OuterObjectWithEnumProperty
from petstore_api.models.parent import Parent
from petstore_api.models.parent_with_optional_dict import ParentWithOptionalDict
from petstore_api.models.pet import Pet
from petstore_api.models.pig import Pig

View File

@ -83,7 +83,12 @@ class MixedPropertiesAndAdditionalPropertiesClass(BaseModel):
_obj = MixedPropertiesAndAdditionalPropertiesClass.parse_obj({
"uuid": obj.get("uuid"),
"date_time": obj.get("dateTime"),
"map": dict((_k, Animal.from_dict(_v)) for _k, _v in obj.get("map").items()) if obj.get("map") is not None else None
"map": dict(
(_k, Animal.from_dict(_v))
for _k, _v in obj.get("map").items()
)
if obj.get("map") is not None
else None
})
# store additional fields in additional_properties
for _key in obj.keys():

View File

@ -0,0 +1,95 @@
# coding: utf-8
"""
OpenAPI Petstore
This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501
The version of the OpenAPI document: 1.0.0
Generated by OpenAPI Generator (https://openapi-generator.tech)
Do not edit the class manually.
"""
from __future__ import annotations
from inspect import getfullargspec
import pprint
import re # noqa: F401
import json
from typing import Dict, Optional
from pydantic import BaseModel, Field
from petstore_api.models.inner_dict_with_property import InnerDictWithProperty
class Parent(BaseModel):
"""
Parent
"""
optional_dict: Optional[Dict[str, InnerDictWithProperty]] = Field(None, alias="optionalDict")
additional_properties: Dict[str, Any] = {}
__properties = ["optionalDict"]
class Config:
allow_population_by_field_name = True
validate_assignment = True
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) -> Parent:
"""Create an instance of Parent 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={
"additional_properties"
},
exclude_none=True)
# override the default output from pydantic by calling `to_dict()` of each value in optional_dict (dict)
_field_dict = {}
if self.optional_dict:
for _key in self.optional_dict:
if self.optional_dict[_key]:
_field_dict[_key] = self.optional_dict[_key].to_dict()
_dict['optionalDict'] = _field_dict
# 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
return _dict
@classmethod
def from_dict(cls, obj: dict) -> Parent:
"""Create an instance of Parent from a dict"""
if obj is None:
return None
if type(obj) is not dict:
return Parent.parse_obj(obj)
_obj = Parent.parse_obj({
"optional_dict": dict(
(_k, InnerDictWithProperty.from_dict(_v))
for _k, _v in obj.get("optionalDict").items()
)
if obj.get("optionalDict") is not None
else None
})
# store additional fields in additional_properties
for _key in obj.keys():
if _key not in cls.__properties:
_obj.additional_properties[_key] = obj.get(_key)
return _obj

View File

@ -79,7 +79,12 @@ class ParentWithOptionalDict(BaseModel):
return ParentWithOptionalDict.parse_obj(obj)
_obj = ParentWithOptionalDict.parse_obj({
"optional_dict": dict((_k, InnerDictWithProperty.from_dict(_v)) for _k, _v in obj.get("optionalDict").items()) if obj.get("optionalDict") is not None else None
"optional_dict": dict(
(_k, InnerDictWithProperty.from_dict(_v))
for _k, _v in obj.get("optionalDict").items()
)
if obj.get("optionalDict") is not None
else None
})
# store additional fields in additional_properties
for _key in obj.keys():

View File

@ -0,0 +1,57 @@
# coding: utf-8
"""
OpenAPI Petstore
This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501
The version of the OpenAPI document: 1.0.0
Generated by OpenAPI Generator (https://openapi-generator.tech)
Do not edit the class manually.
"""
import unittest
import datetime
import petstore_api
from petstore_api.models.parent import Parent # noqa: E501
from petstore_api.rest import ApiException
class TestParent(unittest.TestCase):
"""Parent unit test stubs"""
def setUp(self):
pass
def tearDown(self):
pass
def make_instance(self, include_optional):
"""Test Parent
include_option is a boolean, when False only required
params are included, when True both required and
optional params are included """
# uncomment below to create an instance of `Parent`
"""
model = petstore_api.models.parent.Parent() # noqa: E501
if include_optional :
return Parent(
optional_dict = {
'key' : petstore_api.models.inner_dict_with_property.InnerDictWithProperty(
a_property = petstore_api.models.a_property.aProperty(), )
}
)
else :
return Parent(
)
"""
def testParent(self):
"""Test Parent"""
# inst_req_only = self.make_instance(include_optional=False)
# inst_req_and_optional = self.make_instance(include_optional=True)
if __name__ == '__main__':
unittest.main()

View File

@ -407,3 +407,9 @@ class ModelTests(unittest.TestCase):
b = petstore_api.ParentWithOptionalDict.from_dict({"optionalDict": {"key": {"aProperty": {"a": "b"}}}})
self.assertFalse(b is None)
self.assertEqual(b.optional_dict["key"].a_property["a"], "b")
def test_object_with_dict_of_dict_of_object(self):
# for https://github.com/OpenAPITools/openapi-generator/issues/15135
d = {"optionalDict": {"a": {"b": {"aProperty": "value"}}}}
a = petstore_api.Parent.from_dict(d)
self.assertEqual(a.to_dict(), d)