Last active
March 5, 2018 01:45
-
-
Save jmcarp/ea3df34b3f68b15e27a2 to your computer and use it in GitHub Desktop.
marshmallow-models
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import six | |
import inflection | |
import marshmallow as ma | |
class Model(object): | |
def __init__(self, **kwargs): | |
self._schema = self.Schema() | |
self.load(**kwargs) | |
def load(self, **kwargs): | |
data = {key: None for key in self._schema.fields} | |
data.update(self._schema.load(kwargs).data) | |
self.__dict__.update(data) | |
def dump(self): | |
return self._schema.dump(self).data | |
class InflectSchema(ma.Schema): | |
@ma.pre_load | |
def pre_load(self, data): | |
return { | |
inflection.underscore(key): value | |
for key, value in six.iteritems(data) | |
} | |
@ma.post_dump | |
def post_dump(self, data): | |
return { | |
inflection.camelize(key, uppercase_first_letter=False): value | |
for key, value in six.iteritems(data) | |
} | |
class Cat(Model): | |
class Schema(InflectSchema): | |
name = ma.fields.String() | |
fave_food = ma.fields.String() | |
cat = Cat(name='calici', faveFood='pellets') |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment