8000 fix: Support discriminator for deserializing polymorphic types by yoavk · Pull Request #717 · openapi-generators/openapi-python-client · GitHub
[go: up one dir, main page]

Skip to content

fix: Support discriminator for deserializing polymorphic types #717

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

Closed
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.
8000 Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
19 changes: 19 additions & 0 deletions openapi_python_client/parser/properties/__init__.py
8000
Original file line number Diff line number Diff line change
Expand Up @@ -223,6 +223,8 @@ class UnionProperty(Property):
"""A property representing a Union (anyOf) of other properties"""

inner_properties: List[Property]
discriminator: Optional[oai.openapi_schema_pydantic.Discriminator] = None

template: ClassVar[str] = "union_property.py.jinja"

def _get_inner_type_strings(self, json: bool = False) -> Set[str]:
Expand Down Expand Up @@ -300,6 +302,22 @@ def get_lazy_imports(self, *, prefix: str) -> Set[str]:
lazy_imports.update(inner_prop.get_lazy_imports(prefix=prefix))
return lazy_imports

def get_discriminator_value(self, sub_model: ModelProperty) -> str:
"""
Get discriminator's property value for sub_model
"""
if self.discriminator:
if self.discriminator.mapping:
for property_value, schema_path in self.discriminator.mapping.items():
ref_path = parse_reference_path(schema_path)
if isinstance(ref_path, ParseError):
raise TypeError()
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I try, when at all possible, not to raise anything since it usually results in a poor error message for the consumer—who usually has no idea why the OpenAPI Document is wrong (I should probably add a code style section to the contribution guide).

I think in this case, it might be a good idea to create a new property type DiscriminatedProperty or similar, since we should handle it in a few different ways:

  1. We must enforce at parse time (return a ParseError if it fails) that every type within the union is a ModelProperty with a required property matching the discriminator
  2. Instead of trying every inner property at runtime, we only attempt the build the one matching the discriminator. So instead of a bunch of try/except, there will be an if statement or, better yet, a dict to look up the correct class.

if ref_path in sub_model.roots:
return property_value
else:
return sub_model.get_base_type_string()
raise TypeError()


def _string_based_property(
name: str, required: bool, data: oai.Schema, config: Config
Expand Down Expand Up @@ -509,6 +527,7 @@ def build_union_property(
python_name=utils.PythonIdentifier(value=name, prefix=config.field_prefix),
description=data.description,
example=data.example,
discriminator=data.discriminator,
),
schemas,
)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@
{% endmacro %}

{% macro check_type_for_construct(property, source) %}isinstance({{ source }}, dict){% endmacro %}
{% macro check_discriminator(source, property_name, discriminator_value) %}{{ source }}["{{ property_name }}"] == "{{ discriminator_value }}"{% endmacro %}

{% macro transform(property, source, destination, declare_type=True, multipart=False, transform_method="to_dict") %}
{% set transformed = source + "." + transform_method + "()" %}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,10 @@ def _parse_{{ property.python_name }}(data: object) -> {{ property.get_type_stri
try:
if not {{ inner_template.check_type_for_construct(inner_property, "data") }}:
raise TypeError()
{% if property.discriminator and inner_template.check_discriminator %}
if not {{ inner_template.check_discriminator("data", property.discriminator.propertyName, property.get_discriminator_value(inner_property)) }}:
raise TypeError()
{% endif %}
{{ inner_template.construct(inner_property, "data", initial_value="UNSET") | indent(8) }}
return {{ inner_property.python_name }}
except: # noqa: E722
Expand All @@ -28,6 +32,10 @@ def _parse_{{ property.python_name }}(data: object) -> {{ property.get_type_stri
if not {{ inner_template.check_type_for_construct(inner_property, "data") }}:
raise TypeError()
{% endif %}
{% if property.discriminator and inner_template.check_discriminator %}
if not {{ inner_template.check_discriminator("data", property.discriminator.propertyName, property.get_discriminator_value(inner_property)) }}:
raise TypeError()
{% endif %}
{{ inner_template.construct(inner_property, "data", initial_value="UNSET") | indent(4) }}
return {{ inner_property.python_name }}
{% endif %}
Expand Down
0