Create a model from YAML/JSON on the fly Create a model from YAML/JSON on the fly mongodb mongodb

Create a model from YAML/JSON on the fly


If you're going to use YAML, pyyaml is completely painless, and automatically outputs a data structure using python's built-in types (or even more complex types that you define).

Any way you go, I would also highly recommend Rx as a validator so you can easily verify the integrity of the loaded files.*

As for using this to create a model you can use the built-in function type (not type(object), but type(name, bases, dict)) which... "[r]eturn a new type object. This is essentially a dynamic form of the class statement."

So, you can call:

def massage(fields_dict):    #transform your file format into a valid set of fields, and return ituser_class = type(yaml_data['model'], Document, massage(yaml_data['fields']) )

*I've used both of these together in the last eight hours, coincidentally - they work together painlessly, e.g.:

import yamlimport Rxdata = yaml.load(open("foo.yaml")rx = Rx.Factory({ "register_core_types": True })schema = rx.make_schema(yaml.load(open("schema.yaml")))if not schema.check(data):    raise ValueError("data file contents are not in a valid format")