Created
November 20, 2015 23:04
-
-
Save rafaelhbarros/574181353190c1aee46d to your computer and use it in GitHub Desktop.
Schematic soft validation
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
from __future__ import absolute_import, print_function, unicode_literals | |
import schematics | |
from datetime import datetime as Datetime | |
import datetime | |
# Third party imports | |
from bson.objectid import ObjectId | |
from schematics.models import Model as BaseModel | |
from schematics.types import * | |
from schematics.types.compound import * | |
class Model(BaseModel): | |
def to_dict(self): | |
return self.to_native() | |
class ObjectIdType(BaseType): | |
def to_native(self, value, context=None): | |
return ObjectId(value) | |
def to_primitive(self, value, context=None): | |
return str(value) | |
class User(Model): | |
_username = StringType() | |
test = StringType() | |
def __init__(self, data, *args, **kwargs): | |
_this_keys = set(self.keys()) | |
for key in data.keys(): | |
if key not in _this_keys: | |
print( | |
"WARNING: Attribute '{}' not present in class: {}".format( | |
key, self.__class__.__name__)) | |
data.pop(key) | |
super(User, self).__init__(data, *args, **kwargs) | |
if __name__ == '__main__': | |
u = User({'_username': 'username', 'test': 'test'}) | |
u.validate() | |
print(u) | |
u = User({'_username': 'username', 'test': 'test', 'unknown': 'unknown'}) | |
u.validate() | |
print(u) | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment