[python] Fix map of array in property (#15844)

* fix map of array in property (python)

* update samples
This commit is contained in:
William Cheng
2023-06-15 11:50:56 +08:00
committed by GitHub
parent afca85acf5
commit b42234eb3c
17 changed files with 407 additions and 6 deletions

View File

@@ -151,6 +151,18 @@ class {{classname}}({{#parent}}{{{.}}}{{/parent}}{{^parent}}BaseModel{{/parent}}
{{/items.isPrimitiveType}}
{{/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)
@@ -162,6 +174,7 @@ class {{classname}}({{#parent}}{{{.}}}{{/parent}}{{^parent}}BaseModel{{/parent}}
_dict['{{{baseName}}}'] = _field_dict
{{/items.isEnumOrRef}}
{{/items.isPrimitiveType}}
{{/items.isArray}}
{{/isMap}}
{{/isContainer}}
{{^isContainer}}
@@ -260,15 +273,13 @@ class {{classname}}({{#parent}}{{{.}}}{{/parent}}{{^parent}}BaseModel{{/parent}}
{{/items.isMap}}
{{#items.isArray}}
"{{{name}}}": dict(
(_k, [(_ik, {{{items.items.dataType}}}.from_dict(_iv))]
for _ik, _iv in _v.items()
(_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()
)
if obj.get("{{{baseName}}}") is not None
else None{{^-last}},{{/-last}}
{{/items.isArray}}
{{/items.isContainer}}
{{^items.isContainer}}

View File

@@ -2212,3 +2212,12 @@ components:
type: string
nullable: true
pattern: "^[A-Z].*"
MapOfArrayOfModel:
type: object
properties:
shopIdToOrgOnlineLipMap:
additionalProperties:
type: array
items:
$ref: "#/components/schemas/Tag"

View File

@@ -44,6 +44,7 @@ docs/HealthCheckResult.md
docs/InnerDictWithProperty.md
docs/IntOrString.md
docs/List.md
docs/MapOfArrayOfModel.md
docs/MapTest.md
docs/MixedPropertiesAndAdditionalPropertiesClass.md
docs/Model200Response.md
@@ -130,6 +131,7 @@ petstore_api/models/health_check_result.py
petstore_api/models/inner_dict_with_property.py
petstore_api/models/int_or_string.py
petstore_api/models/list.py
petstore_api/models/map_of_array_of_model.py
petstore_api/models/map_test.py
petstore_api/models/mixed_properties_and_additional_properties_class.py
petstore_api/models/model200_response.py

View File

@@ -169,6 +169,7 @@ Class | Method | HTTP request | Description
- [InnerDictWithProperty](docs/InnerDictWithProperty.md)
- [IntOrString](docs/IntOrString.md)
- [List](docs/List.md)
- [MapOfArrayOfModel](docs/MapOfArrayOfModel.md)
- [MapTest](docs/MapTest.md)
- [MixedPropertiesAndAdditionalPropertiesClass](docs/MixedPropertiesAndAdditionalPropertiesClass.md)
- [Model200Response](docs/Model200Response.md)

View File

@@ -0,0 +1,28 @@
# MapOfArrayOfModel
## Properties
Name | Type | Description | Notes
------------ | ------------- | ------------- | -------------
**shop_id_to_org_online_lip_map** | **Dict[str, List[Tag]]** | | [optional]
## Example
```python
from petstore_api.models.map_of_array_of_model import MapOfArrayOfModel
# TODO update the JSON string below
json = "{}"
# create an instance of MapOfArrayOfModel from a JSON string
map_of_array_of_model_instance = MapOfArrayOfModel.from_json(json)
# print the JSON string representation of the object
print MapOfArrayOfModel.to_json()
# convert the object into a dict
map_of_array_of_model_dict = map_of_array_of_model_instance.to_dict()
# create an instance of MapOfArrayOfModel from a dict
map_of_array_of_model_form_dict = map_of_array_of_model.from_dict(map_of_array_of_model_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

@@ -75,6 +75,7 @@ from petstore_api.models.health_check_result import HealthCheckResult
from petstore_api.models.inner_dict_with_property import InnerDictWithProperty
from petstore_api.models.int_or_string import IntOrString
from petstore_api.models.list import List
from petstore_api.models.map_of_array_of_model import MapOfArrayOfModel
from petstore_api.models.map_test import MapTest
from petstore_api.models.mixed_properties_and_additional_properties_class import MixedPropertiesAndAdditionalPropertiesClass
from petstore_api.models.model200_response import Model200Response

View File

@@ -51,6 +51,7 @@ from petstore_api.models.health_check_result import HealthCheckResult
from petstore_api.models.inner_dict_with_property import InnerDictWithProperty
from petstore_api.models.int_or_string import IntOrString
from petstore_api.models.list import List
from petstore_api.models.map_of_array_of_model import MapOfArrayOfModel
from petstore_api.models.map_test import MapTest
from petstore_api.models.mixed_properties_and_additional_properties_class import MixedPropertiesAndAdditionalPropertiesClass
from petstore_api.models.model200_response import Model200Response

View File

@@ -0,0 +1,87 @@
# 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
import pprint
import re # noqa: F401
import json
from typing import Dict, List, Optional
from pydantic import BaseModel, Field, conlist
from petstore_api.models.tag import Tag
class MapOfArrayOfModel(BaseModel):
"""
MapOfArrayOfModel
"""
shop_id_to_org_online_lip_map: Optional[Dict[str, conlist(Tag)]] = Field(None, alias="shopIdToOrgOnlineLipMap")
__properties = ["shopIdToOrgOnlineLipMap"]
class Config:
"""Pydantic configuration"""
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) -> MapOfArrayOfModel:
"""Create an instance of MapOfArrayOfModel 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 shop_id_to_org_online_lip_map (dict of array)
_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]:
_field_dict_of_array[_key] = [
_item.to_dict() for _item in self.shop_id_to_org_online_lip_map[_key]
]
_dict['shopIdToOrgOnlineLipMap'] = _field_dict_of_array
return _dict
@classmethod
def from_dict(cls, obj: dict) -> MapOfArrayOfModel:
"""Create an instance of MapOfArrayOfModel from a dict"""
if obj is None:
return None
if not isinstance(obj, dict):
return MapOfArrayOfModel.parse_obj(obj)
_obj = MapOfArrayOfModel.parse_obj({
"shop_id_to_org_online_lip_map": dict(
(_k,
[Tag.from_dict(_item) for _item in _v]
if _v is not None
else None
)
for _k, _v in obj.get("shopIdToOrgOnlineLipMap").items()
)
})
return _obj

View File

@@ -0,0 +1,60 @@
# 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.map_of_array_of_model import MapOfArrayOfModel # noqa: E501
from petstore_api.rest import ApiException
class TestMapOfArrayOfModel(unittest.TestCase):
"""MapOfArrayOfModel unit test stubs"""
def setUp(self):
pass
def tearDown(self):
pass
def make_instance(self, include_optional):
"""Test MapOfArrayOfModel
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 `MapOfArrayOfModel`
"""
model = petstore_api.models.map_of_array_of_model.MapOfArrayOfModel() # noqa: E501
if include_optional :
return MapOfArrayOfModel(
shop_id_to_org_online_lip_map = {
'key' : [
petstore_api.models.tag.Tag(
id = 56,
name = '', )
]
}
)
else :
return MapOfArrayOfModel(
)
"""
def testMapOfArrayOfModel(self):
"""Test MapOfArrayOfModel"""
# 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

@@ -44,6 +44,7 @@ docs/HealthCheckResult.md
docs/InnerDictWithProperty.md
docs/IntOrString.md
docs/List.md
docs/MapOfArrayOfModel.md
docs/MapTest.md
docs/MixedPropertiesAndAdditionalPropertiesClass.md
docs/Model200Response.md
@@ -130,6 +131,7 @@ petstore_api/models/health_check_result.py
petstore_api/models/inner_dict_with_property.py
petstore_api/models/int_or_string.py
petstore_api/models/list.py
petstore_api/models/map_of_array_of_model.py
petstore_api/models/map_test.py
petstore_api/models/mixed_properties_and_additional_properties_class.py
petstore_api/models/model200_response.py

View File

@@ -169,6 +169,7 @@ Class | Method | HTTP request | Description
- [InnerDictWithProperty](docs/InnerDictWithProperty.md)
- [IntOrString](docs/IntOrString.md)
- [List](docs/List.md)
- [MapOfArrayOfModel](docs/MapOfArrayOfModel.md)
- [MapTest](docs/MapTest.md)
- [MixedPropertiesAndAdditionalPropertiesClass](docs/MixedPropertiesAndAdditionalPropertiesClass.md)
- [Model200Response](docs/Model200Response.md)

View File

@@ -0,0 +1,28 @@
# MapOfArrayOfModel
## Properties
Name | Type | Description | Notes
------------ | ------------- | ------------- | -------------
**shop_id_to_org_online_lip_map** | **Dict[str, List[Tag]]** | | [optional]
## Example
```python
from petstore_api.models.map_of_array_of_model import MapOfArrayOfModel
# TODO update the JSON string below
json = "{}"
# create an instance of MapOfArrayOfModel from a JSON string
map_of_array_of_model_instance = MapOfArrayOfModel.from_json(json)
# print the JSON string representation of the object
print MapOfArrayOfModel.to_json()
# convert the object into a dict
map_of_array_of_model_dict = map_of_array_of_model_instance.to_dict()
# create an instance of MapOfArrayOfModel from a dict
map_of_array_of_model_form_dict = map_of_array_of_model.from_dict(map_of_array_of_model_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

@@ -75,6 +75,7 @@ from petstore_api.models.health_check_result import HealthCheckResult
from petstore_api.models.inner_dict_with_property import InnerDictWithProperty
from petstore_api.models.int_or_string import IntOrString
from petstore_api.models.list import List
from petstore_api.models.map_of_array_of_model import MapOfArrayOfModel
from petstore_api.models.map_test import MapTest
from petstore_api.models.mixed_properties_and_additional_properties_class import MixedPropertiesAndAdditionalPropertiesClass
from petstore_api.models.model200_response import Model200Response

View File

@@ -51,6 +51,7 @@ from petstore_api.models.health_check_result import HealthCheckResult
from petstore_api.models.inner_dict_with_property import InnerDictWithProperty
from petstore_api.models.int_or_string import IntOrString
from petstore_api.models.list import List
from petstore_api.models.map_of_array_of_model import MapOfArrayOfModel
from petstore_api.models.map_test import MapTest
from petstore_api.models.mixed_properties_and_additional_properties_class import MixedPropertiesAndAdditionalPropertiesClass
from petstore_api.models.model200_response import Model200Response

View File

@@ -0,0 +1,99 @@
# 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
import pprint
import re # noqa: F401
import json
from typing import Dict, List, Optional
from pydantic import BaseModel, Field, conlist
from petstore_api.models.tag import Tag
class MapOfArrayOfModel(BaseModel):
"""
MapOfArrayOfModel
"""
shop_id_to_org_online_lip_map: Optional[Dict[str, conlist(Tag)]] = Field(None, alias="shopIdToOrgOnlineLipMap")
additional_properties: Dict[str, Any] = {}
__properties = ["shopIdToOrgOnlineLipMap"]
class Config:
"""Pydantic configuration"""
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) -> MapOfArrayOfModel:
"""Create an instance of MapOfArrayOfModel 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 shop_id_to_org_online_lip_map (dict of array)
_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]:
_field_dict_of_array[_key] = [
_item.to_dict() for _item in self.shop_id_to_org_online_lip_map[_key]
]
_dict['shopIdToOrgOnlineLipMap'] = _field_dict_of_array
# 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) -> MapOfArrayOfModel:
"""Create an instance of MapOfArrayOfModel from a dict"""
if obj is None:
return None
if not isinstance(obj, dict):
return MapOfArrayOfModel.parse_obj(obj)
_obj = MapOfArrayOfModel.parse_obj({
"shop_id_to_org_online_lip_map": dict(
(_k,
[Tag.from_dict(_item) for _item in _v]
if _v is not None
else None
)
for _k, _v in obj.get("shopIdToOrgOnlineLipMap").items()
)
})
# 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

@@ -0,0 +1,60 @@
# 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.map_of_array_of_model import MapOfArrayOfModel # noqa: E501
from petstore_api.rest import ApiException
class TestMapOfArrayOfModel(unittest.TestCase):
"""MapOfArrayOfModel unit test stubs"""
def setUp(self):
pass
def tearDown(self):
pass
def make_instance(self, include_optional):
"""Test MapOfArrayOfModel
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 `MapOfArrayOfModel`
"""
model = petstore_api.models.map_of_array_of_model.MapOfArrayOfModel() # noqa: E501
if include_optional :
return MapOfArrayOfModel(
shop_id_to_org_online_lip_map = {
'key' : [
petstore_api.models.tag.Tag(
id = 56,
name = '', )
]
}
)
else :
return MapOfArrayOfModel(
)
"""
def testMapOfArrayOfModel(self):
"""Test MapOfArrayOfModel"""
# 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

@@ -483,3 +483,12 @@ class ModelTests(unittest.TestCase):
a = petstore_api.IntOrString(1)
except ValueError as e:
self.assertTrue("ensure this value is greater than or equal to 10" in str(e))
def test_map_of_array_of_model(self):
a = petstore_api.MapOfArrayOfModel()
t = petstore_api.Tag(id=123, name="tag name")
a.shop_id_to_org_online_lip_map = {"somekey": [t]}
self.assertEqual(a.to_dict(), {'shopIdToOrgOnlineLipMap': {'somekey': [{'id': 123, 'name': 'tag name'}]}})
self.assertEqual(a.to_json(), '{"shopIdToOrgOnlineLipMap": {"somekey": [{"id": 123, "name": "tag name"}]}}')
a2 = petstore_api.MapOfArrayOfModel.from_dict(a.to_dict())
self.assertEqual(a.to_dict(), a2.to_dict())