Skip to content

Commit

Permalink
[python] Fix unnamed dicts with additional properties (#16779)
Browse files Browse the repository at this point in the history
* test: Add two extra models for testing

* Fix unnamed dicts with additional properties

Closes #16630
  • Loading branch information
robertschweizer authored Oct 11, 2023
1 parent 7af4593 commit f180aa0
Show file tree
Hide file tree
Showing 45 changed files with 1,500 additions and 3 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -182,15 +182,17 @@ class {{classname}}({{#parent}}{{{.}}}{{/parent}}{{^parent}}BaseModel{{/parent}}
{{/isArray}}
{{#isMap}}
{{#items.isArray}}
{{^items.items.isPrimitiveType}}
# 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]:
if self.{{{name}}}[_key] is not None:
_field_dict_of_array[_key] = [
_item.to_dict() for _item in self.{{{name}}}[_key]
]
_dict['{{{baseName}}}'] = _field_dict_of_array
{{/items.items.isPrimitiveType}}
{{/items.isArray}}
{{^items.isArray}}
{{^items.isPrimitiveType}}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2351,3 +2351,21 @@ components:
title: ListOfObjects
items:
$ref: "#/components/schemas/Tag"
UnnamedDictWithAdditionalStringListProperties:
type: object
properties:
dictProperty:
type: object
additionalProperties:
type: array
items:
type: string
UnnamedDictWithAdditionalModelListProperties:
type: object
properties:
dictProperty:
type: object
additionalProperties:
type: array
items:
$ref: "#/components/schemas/CreatureInfo"
Original file line number Diff line number Diff line change
Expand Up @@ -86,6 +86,8 @@ docs/StoreApi.md
docs/Tag.md
docs/TestInlineFreeformAdditionalPropertiesRequest.md
docs/Tiger.md
docs/UnnamedDictWithAdditionalModelListProperties.md
docs/UnnamedDictWithAdditionalStringListProperties.md
docs/User.md
docs/UserApi.md
docs/WithNestedOneOf.md
Expand Down Expand Up @@ -181,6 +183,8 @@ petstore_api/models/special_name.py
petstore_api/models/tag.py
petstore_api/models/test_inline_freeform_additional_properties_request.py
petstore_api/models/tiger.py
petstore_api/models/unnamed_dict_with_additional_model_list_properties.py
petstore_api/models/unnamed_dict_with_additional_string_list_properties.py
petstore_api/models/user.py
petstore_api/models/with_nested_one_of.py
petstore_api/py.typed
Expand Down
2 changes: 2 additions & 0 deletions samples/openapi3/client/petstore/python-aiohttp/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -212,6 +212,8 @@ Class | Method | HTTP request | Description
- [Tag](docs/Tag.md)
- [TestInlineFreeformAdditionalPropertiesRequest](docs/TestInlineFreeformAdditionalPropertiesRequest.md)
- [Tiger](docs/Tiger.md)
- [UnnamedDictWithAdditionalModelListProperties](docs/UnnamedDictWithAdditionalModelListProperties.md)
- [UnnamedDictWithAdditionalStringListProperties](docs/UnnamedDictWithAdditionalStringListProperties.md)
- [User](docs/User.md)
- [WithNestedOneOf](docs/WithNestedOneOf.md)

Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
# UnnamedDictWithAdditionalModelListProperties


## Properties
Name | Type | Description | Notes
------------ | ------------- | ------------- | -------------
**dict_property** | **Dict[str, List[CreatureInfo]]** | | [optional]

## Example

```python
from petstore_api.models.unnamed_dict_with_additional_model_list_properties import UnnamedDictWithAdditionalModelListProperties

# TODO update the JSON string below
json = "{}"
# create an instance of UnnamedDictWithAdditionalModelListProperties from a JSON string
unnamed_dict_with_additional_model_list_properties_instance = UnnamedDictWithAdditionalModelListProperties.from_json(json)
# print the JSON string representation of the object
print UnnamedDictWithAdditionalModelListProperties.to_json()

# convert the object into a dict
unnamed_dict_with_additional_model_list_properties_dict = unnamed_dict_with_additional_model_list_properties_instance.to_dict()
# create an instance of UnnamedDictWithAdditionalModelListProperties from a dict
unnamed_dict_with_additional_model_list_properties_form_dict = unnamed_dict_with_additional_model_list_properties.from_dict(unnamed_dict_with_additional_model_list_properties_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)


Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
# UnnamedDictWithAdditionalStringListProperties


## Properties
Name | Type | Description | Notes
------------ | ------------- | ------------- | -------------
**dict_property** | **Dict[str, List[str]]** | | [optional]

## Example

```python
from petstore_api.models.unnamed_dict_with_additional_string_list_properties import UnnamedDictWithAdditionalStringListProperties

# TODO update the JSON string below
json = "{}"
# create an instance of UnnamedDictWithAdditionalStringListProperties from a JSON string
unnamed_dict_with_additional_string_list_properties_instance = UnnamedDictWithAdditionalStringListProperties.from_json(json)
# print the JSON string representation of the object
print UnnamedDictWithAdditionalStringListProperties.to_json()

# convert the object into a dict
unnamed_dict_with_additional_string_list_properties_dict = unnamed_dict_with_additional_string_list_properties_instance.to_dict()
# create an instance of UnnamedDictWithAdditionalStringListProperties from a dict
unnamed_dict_with_additional_string_list_properties_form_dict = unnamed_dict_with_additional_string_list_properties.from_dict(unnamed_dict_with_additional_string_list_properties_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)


Original file line number Diff line number Diff line change
Expand Up @@ -115,5 +115,7 @@
from petstore_api.models.tag import Tag
from petstore_api.models.test_inline_freeform_additional_properties_request import TestInlineFreeformAdditionalPropertiesRequest
from petstore_api.models.tiger import Tiger
from petstore_api.models.unnamed_dict_with_additional_model_list_properties import UnnamedDictWithAdditionalModelListProperties
from petstore_api.models.unnamed_dict_with_additional_string_list_properties import UnnamedDictWithAdditionalStringListProperties
from petstore_api.models.user import User
from petstore_api.models.with_nested_one_of import WithNestedOneOf
Original file line number Diff line number Diff line change
Expand Up @@ -91,5 +91,7 @@
from petstore_api.models.tag import Tag
from petstore_api.models.test_inline_freeform_additional_properties_request import TestInlineFreeformAdditionalPropertiesRequest
from petstore_api.models.tiger import Tiger
from petstore_api.models.unnamed_dict_with_additional_model_list_properties import UnnamedDictWithAdditionalModelListProperties
from petstore_api.models.unnamed_dict_with_additional_string_list_properties import UnnamedDictWithAdditionalStringListProperties
from petstore_api.models.user import User
from petstore_api.models.with_nested_one_of import WithNestedOneOf
Original file line number Diff line number Diff line change
Expand Up @@ -75,7 +75,7 @@ def to_dict(self) -> Dict[str, Any]:
_field_dict_of_array = {}
if self.shop_id_to_org_online_lip_map:
for _key in self.shop_id_to_org_online_lip_map:
if self.shop_id_to_org_online_lip_map[_key]:
if self.shop_id_to_org_online_lip_map[_key] is not None:
_field_dict_of_array[_key] = [
_item.to_dict() for _item in self.shop_id_to_org_online_lip_map[_key]
]
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,96 @@
# 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: \" \\
The version of the OpenAPI document: 1.0.0
Generated by OpenAPI Generator (https://openapi-generator.tech)
Do not edit the class manually.
""" # noqa: E501


from __future__ import annotations
import pprint
import re # noqa: F401
import json


from typing import Dict, List, Optional
from pydantic import BaseModel
from pydantic import Field
from petstore_api.models.creature_info import CreatureInfo
from typing import Dict, Any
try:
from typing import Self
except ImportError:
from typing_extensions import Self

class UnnamedDictWithAdditionalModelListProperties(BaseModel):
"""
UnnamedDictWithAdditionalModelListProperties
"""
dict_property: Optional[Dict[str, List[CreatureInfo]]] = Field(default=None, alias="dictProperty")
__properties: ClassVar[List[str]] = ["dictProperty"]

model_config = {
"populate_by_name": True,
"validate_assignment": True
}


def to_str(self) -> str:
"""Returns the string representation of the model using alias"""
return pprint.pformat(self.model_dump(by_alias=True))

def to_json(self) -> str:
"""Returns the JSON representation of the model using alias"""
# TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead
return json.dumps(self.to_dict())

@classmethod
def from_json(cls, json_str: str) -> Self:
"""Create an instance of UnnamedDictWithAdditionalModelListProperties 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.model_dump(by_alias=True,
exclude={
},
exclude_none=True)
# override the default output from pydantic by calling `to_dict()` of each value in dict_property (dict of array)
_field_dict_of_array = {}
if self.dict_property:
for _key in self.dict_property:
if self.dict_property[_key] is not None:
_field_dict_of_array[_key] = [
_item.to_dict() for _item in self.dict_property[_key]
]
_dict['dictProperty'] = _field_dict_of_array
return _dict

@classmethod
def from_dict(cls, obj: dict) -> Self:
"""Create an instance of UnnamedDictWithAdditionalModelListProperties from a dict"""
if obj is None:
return None

if not isinstance(obj, dict):
return cls.model_validate(obj)

_obj = cls.model_validate({
"dictProperty": dict(
(_k,
[CreatureInfo.from_dict(_item) for _item in _v]
if _v is not None
else None
)
for _k, _v in obj.get("dictProperty").items()
)
})
return _obj


Original file line number Diff line number Diff line change
@@ -0,0 +1,79 @@
# 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: \" \\
The version of the OpenAPI document: 1.0.0
Generated by OpenAPI Generator (https://openapi-generator.tech)
Do not edit the class manually.
""" # noqa: E501


from __future__ import annotations
import pprint
import re # noqa: F401
import json


from typing import Dict, List, Optional
from pydantic import BaseModel, StrictStr
from pydantic import Field
from typing import Dict, Any
try:
from typing import Self
except ImportError:
from typing_extensions import Self

class UnnamedDictWithAdditionalStringListProperties(BaseModel):
"""
UnnamedDictWithAdditionalStringListProperties
"""
dict_property: Optional[Dict[str, List[StrictStr]]] = Field(default=None, alias="dictProperty")
__properties: ClassVar[List[str]] = ["dictProperty"]

model_config = {
"populate_by_name": True,
"validate_assignment": True
}


def to_str(self) -> str:
"""Returns the string representation of the model using alias"""
return pprint.pformat(self.model_dump(by_alias=True))

def to_json(self) -> str:
"""Returns the JSON representation of the model using alias"""
# TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead
return json.dumps(self.to_dict())

@classmethod
def from_json(cls, json_str: str) -> Self:
"""Create an instance of UnnamedDictWithAdditionalStringListProperties 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.model_dump(by_alias=True,
exclude={
},
exclude_none=True)
return _dict

@classmethod
def from_dict(cls, obj: dict) -> Self:
"""Create an instance of UnnamedDictWithAdditionalStringListProperties from a dict"""
if obj is None:
return None

if not isinstance(obj, dict):
return cls.model_validate(obj)

_obj = cls.model_validate({
"dictProperty": obj.get("dictProperty")
})
return _obj


Original file line number Diff line number Diff line change
@@ -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: \" \\
The version of the OpenAPI document: 1.0.0
Generated by OpenAPI Generator (https://openapi-generator.tech)
Do not edit the class manually.
""" # noqa: E501


import unittest
import datetime

from petstore_api.models.unnamed_dict_with_additional_model_list_properties import UnnamedDictWithAdditionalModelListProperties # noqa: E501

class TestUnnamedDictWithAdditionalModelListProperties(unittest.TestCase):
"""UnnamedDictWithAdditionalModelListProperties unit test stubs"""

def setUp(self):
pass

def tearDown(self):
pass

def make_instance(self, include_optional) -> UnnamedDictWithAdditionalModelListProperties:
"""Test UnnamedDictWithAdditionalModelListProperties
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 `UnnamedDictWithAdditionalModelListProperties`
"""
model = UnnamedDictWithAdditionalModelListProperties() # noqa: E501
if include_optional:
return UnnamedDictWithAdditionalModelListProperties(
dict_property = {
'key' : [
petstore_api.models.creature_info.CreatureInfo(
name = '', )
]
}
)
else:
return UnnamedDictWithAdditionalModelListProperties(
)
"""

def testUnnamedDictWithAdditionalModelListProperties(self):
"""Test UnnamedDictWithAdditionalModelListProperties"""
# inst_req_only = self.make_instance(include_optional=False)
# inst_req_and_optional = self.make_instance(include_optional=True)

if __name__ == '__main__':
unittest.main()
Loading

0 comments on commit f180aa0

Please sign in to comment.