swagger-api / swagger-api/swagger-codegen

[python-flask] from_dict(to_dict(obj)) does not work (snake_case vs CamelCase)

Open
#7,838 3 comments 3 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

Dominant language
Mustache
Stars
17.8k
Forks
6k
PR merge metrics
No merged PRs in 30d

Description

Description

When converting a model to and from a dict, the following command statement does not work.
It removes all the fields being defined as CamelCase in swagger but implemented as snake_case in python.

settings.from_dict(settings.to_dict(obj))
Swagger-codegen version

2.3.1

Swagger declaration file content or url
...
definitions:
  Settings:
    type: object
    properties:
      someArg:
        type: string
...
Command line used for generation
java -jar swagger-codegen-cli-2.3.1.jar generate -i swagger.yml -l python-flask -o flask
Steps to reproduce
settings = Settings(some_args='something')
other_settings = settings.from_dict(settings.to_dict())
# -> other_settings.some_args is None
Related issues/PRs
  • I will create a PR to solve this issue if my fix is accepted by the community
Suggest a fix/enhancement

Replace swagger_server.util.deserialize_model(.) with the following version:

def deserialize_model(data, klass):
    """Deserializes list or dict to model.

    :param data: dict, list.
    :type data: dict | list
    :param klass: class literal.
    :return: model object.
    """
    instance = klass()

    if not instance.swagger_types:
        return data

    for attr, attr_type in six.iteritems(instance.swagger_types):
        if data is not None and isinstance(data, (list, dict)):
            value = None
            if instance.attribute_map[attr] in data:
                value = data[instance.attribute_map[attr]]
            elif attr in data:
                value = data[attr]

            setattr(instance, attr, _deserialize(value, attr_type))

    return instance

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

Locate the Python-Flask template implementation of swagger_server.util.deserialize_model and compare it with the proposed version in the issue. Reproduce the supplied Settings round trip from_dict(to_dict(obj)) and verify that the some_args value survives when the Swagger property is someArg.

Written by the indexing model from the issue text.

Assessment

Tech stack
flask, python
Domain
api, backend
Issue type
Bug
Difficulty
2/5
Estimated time
1-3 hours
Activity status
Stale
Clarity
Mostly clear
Newbie friendliness
35/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.