Skip to content

Instantly share code, notes, and snippets.

@srossross
Last active November 27, 2015 15:53
Show Gist options
  • Save srossross/9982427ca0ae3ea3a120 to your computer and use it in GitHub Desktop.
Save srossross/9982427ca0ae3ea3a120 to your computer and use it in GitHub Desktop.
from schematics.models import Model
from schematics.types import StringType, URLType
from schematics.transforms import import_loop
import warnings
class Foo(Model):
name = StringType()
def __getattr__(self, attr):
return self.__dict__['_initial'].get(attr, None)
def convert(self, instance_or_dict, context=None, partial=True, strict=False,
mapping=None):
cls = self.__class__
def field_converter(field, value, mapping=None):
try:
return field.to_native(value, mapping=mapping)
except Exception as err:
try:
return field.to_native(value)
except Exception as err:
warnings.warn("{} model with id {} has an invalid field '{}': {}".format(
cls.__name__, instance_or_dict.get('_id', '?'),
field.name, err
))
return value
# field_converter = lambda field, value: field.to_native(value)
cls = self.__class__
data = import_loop(cls, instance_or_dict, field_converter, context=context,
partial=partial, strict=strict, mapping=mapping)
return data
f = Foo({'a':1, 'name':1.1}, strict=False)
print f.a
print f.name
@srossross
Copy link
Author

output

In [11]: run partial.py
partial.py:30: UserWarning: Foo model with id ? has an invalid field 'name': [u"Couldn't interpret '1.1' as string."]

1
1.1

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment