Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[Python] handle oneOf/allOf/anyOf composed schemas in the Python client #2121

Closed
wants to merge 5 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -595,4 +595,8 @@ public void removeSelfReferenceImport() {
}
}
}

public boolean isComposed() {
return !allOf.isEmpty() || !oneOf.isEmpty() || !anyOf.isEmpty();
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -72,6 +72,7 @@ class ApiClient(object):
self.cookie = cookie
# Set default User-Agent.
self.user_agent = '{{#httpUserAgent}}{{{.}}}{{/httpUserAgent}}{{^httpUserAgent}}OpenAPI-Generator/{{{packageVersion}}}/python{{/httpUserAgent}}'
self.__deserializer_track = []

def __del__(self):
if self._pool:
Expand Down Expand Up @@ -268,6 +269,7 @@ class ApiClient(object):
"""
if data is None:
return None
self.__deserializer_track.append(klass)

if type(klass) == str:
if klass.startswith('list['):
Expand Down Expand Up @@ -640,6 +642,60 @@ class ApiClient(object):

instance = klass(**kwargs)
rienafairefr marked this conversation as resolved.
Show resolved Hide resolved

if hasattr(instance, 'composed_hierarchy'):
hierarchy = instance.composed_hierarchy
if sum([1 if v else 0 for v in hierarchy.values()]) > 1:
# ignore implicit AllOf
return instance

def error_msg(composed):
return "Failed to parse `{0}` as {1} ({2} {3})" \
.format(data, klass,
composed,
' '.join(hierarchy[composed]))

if hierarchy['allOf']:
matches = []
for sub_klass in hierarchy['allOf']:
try:
if sub_klass in self.__deserializer_track:
# seen it before, break the recursion
matches.append(None)
else:
matches.append(self.__deserialize(data, sub_klass))
except: # noqa: E722
pass
if len(matches) == len(hierarchy['allOf']):
self.__deserializer_track = []
return instance

# not all matched -> error
raise rest.ApiException(status=0, reason=error_msg('allOf'))

if hierarchy['anyOf']:
for sub_klass in hierarchy['anyOf']:
try:
# if at least one of the sub-class matches
# terminate with an instance of this class
return self.__deserialize(data, sub_klass)
except: # noqa: E722
pass
# none matched -> error
raise rest.ApiException(status=0, reason=error_msg('anyOf'))

if hierarchy['oneOf']:
matches = []
for sub_klass in hierarchy['oneOf']:
try:
matches.append(self.__deserialize(data, sub_klass))
except: # noqa: E722
pass
if len(matches) == 1:
return matches[0]

# none matched, or more than one matched -> error
raise rest.ApiException(status=0, reason=error_msg('oneOf'))

if hasattr(instance, 'get_real_child_model'):
klass_name = instance.get_real_child_model(data)
if klass_name:
Expand Down
10 changes: 10 additions & 0 deletions modules/openapi-generator/src/main/resources/python/model.mustache
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,16 @@ class {{classname}}(object):
{{#children}}'{{^vendorExtensions.x-discriminator-value}}{{name}}{{/vendorExtensions.x-discriminator-value}}{{#vendorExtensions.x-discriminator-value}}{{{vendorExtensions.x-discriminator-value}}}{{/vendorExtensions.x-discriminator-value}}': '{{{classname}}}'{{^-last}},
{{/-last}}{{/children}}
}
{{/discriminator}}
{{^discriminator}}
{{#isComposed}}

composed_hierarchy = {
'anyOf': [{{#anyOf}}"{{.}}"{{^-last}}, {{/-last}}{{/anyOf}}],
'allOf': [{{#allOf}}"{{.}}"{{^-last}}, {{/-last}}{{/allOf}}],
'oneOf': [{{#oneOf}}"{{.}}"{{^-last}}, {{/-last}}{{/oneOf}}],
}
{{/isComposed}}
{{/discriminator}}

def __init__(self{{#vars}}, {{name}}={{#defaultValue}}{{{defaultValue}}}{{/defaultValue}}{{^defaultValue}}None{{/defaultValue}}{{/vars}}): # noqa: E501
Expand Down
Loading