schematics icon indicating copy to clipboard operation
schematics copied to clipboard

Exporting mutation?

Open dsully opened this issue 8 years ago • 1 comments

I'm trying to use schematics with a legacy JSON data file format, part of which has a structure such as:

{
  ...
  "external": {
    "click": "pypi:click:6.7",
    "furl": "pypi:furl:1.0.0"
  },
  ...
}

The value for the "external" section can be either a string or another dict value.

This is the modeling I've come up with so far:

class SimpleDependency(Model):
    value = StringType()

    @classmethod
    def _claim_polymorphic(cls, data):
        return 'value' in data


class IvyDependency(Model):

    classifier = StringType()
    configuration = StringType()
    ext = StringType()
    group = StringType(required=True)
    name = StringType(required=True)
    version = StringType(required=True)

    @classmethod
    def _claim_polymorphic(cls, data):
        return 'name' in data and 'group' in data and 'version' in data


class ExternalDependencies(Model):

    dependencies = DictType(PolyModelType([IvyDependency, SimpleDependency]))

    def __init__(self, data, *args, **kwargs):
        
        for k, v in data.items():
            if not isinstance(v, dict):
                data[k] = {'value': v}

        super(ExternalDependencies, self).__init__({'dependencies': data}, *args, **kwargs)

class Spec(Model):

    name = StringType()
    ...
    external = ModelType(ExternalDependencies)
    ....

As you can see, I mutate the data on the way in to conform to these models

I need to be able to serialize the data back into the same format. I don't see any hook (such as Marshmallow's @post_dump decorator) to do so.

Instead I get output as:

"external": {
    "dependencies": {
      "click": {
        "value": "pypi:click:6.7"
      },
      "furl": {
        "value": "pypi:furl:1.0.0"
      }
    }
  },

It's not clear from the documentation or digging around in the source for the correct way to do this.

(Related, if anyone has a better modeling suggestion, I'm all ears).

Thanks

dsully avatar Mar 14 '18 15:03 dsully

Anyone?

dsully avatar Mar 21 '18 02:03 dsully