Skip to content

"openapi.models" and "openapi.enums" aren't usable in custom templates #1188

@eli-bl

Description

@eli-bl

Describe the bug
Among the global Jinja variables set by openapi-python-client is openapi, which is an instance of GeneratorData. That class's attributes include models: Iterator[ModelProperty] and enums: Iterator[Union[EnumProperty, LiteralEnumProperty]].

One might expect that a custom template, for instance models_init.py.jinja, could iterate over those. As far as I can tell, there is no other way for a custom template to find out what all the models and enums are. However, trying to do this never works; the template receives what looks like an empty iterator for both openapi.models and openapi.enums.

I believe the problem is that these iterators have already been iterated, by Project._build_models(), before any custom templates are rendered. They are being set to generator expressions, e.g. models = (prop for prop in schemas.classes_by_name.values() if isinstance(prop, ModelProperty)), rather than list-comprehensions, so once the values have all been run through they can't be restarted.

OpenAPI Spec File
This isn't dependent on the contents of the API spec, but you can reproduce it by adding the following models_init.py.jinja file in end_to_end_tests/test_custom_templates and running pdm regen:

# Should see a list of model class names here
{% for model in openapi.models %}
# {{ model.class_info.name }}
{% endfor %}
# Should see a list of enum class names here
{% for enum in openapi.enums %}
# {{ enum.class_info.name }}
{% endfor %}

The output in models/__init__.py will not show any class names.

Desktop (please complete the following information):

  • OS: macOS 14.7.1
  • Python Version: 3.9.20
  • openapi-python-client version: 0.23.0

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions