From 03ce4601815b5e51cea2e0cab5c9879f773329ed Mon Sep 17 00:00:00 2001 From: Binh Nguyen Date: Tue, 21 May 2013 13:36:44 -0500 Subject: [PATCH] Completed JSON importer. Exported from import matches original data, must be working --- pyaccuwage/__init__.py | 23 +++++++++++++++++++++-- pyaccuwage/fields.py | 15 +++++++++++++++ pyaccuwage/model.py | 19 +++++++++++++++++++ 3 files changed, 55 insertions(+), 2 deletions(-) diff --git a/pyaccuwage/__init__.py b/pyaccuwage/__init__.py index 01fef45..6ea4ccc 100644 --- a/pyaccuwage/__init__.py +++ b/pyaccuwage/__init__.py @@ -94,6 +94,7 @@ def json_dumps(records): import decimal class JSONEncoder(json.JSONEncoder): + def default(self, o): if hasattr(o, 'toJSON') and callable(getattr(o, 'toJSON')): return o.toJSON() @@ -108,13 +109,31 @@ def json_dumps(records): def json_loads(s, record_classes): import json + import fields + import decimal + import re + + if not isinstance(record_classes, dict): + record_classes = dict([ (x.__class__.__name__, x) for x in record_classes]) def object_hook(o): - return {'object_hook':str(o)} + if '__class__' in o: + klass = o['__class__'] + + if klass in record_classes: + return record_classes[klass]().fromJSON(o) + + elif hasattr(fields, klass): + return getattr(fields, klass)().fromJSON(o) + + return o + + #print "OBJECTHOOK", str(o) + #return {'object_hook':str(o)} #def default(self, o): # return super(JSONDecoder, self).default(o) - return json.loads(s, object_hook=object_hook) + return json.loads(s, parse_float=decimal.Decimal, object_hook=object_hook) # THIS WAS IN CONTROLLER, BUT UNLESS WE # REALLY NEED A CONTROLLER CLASS, IT'S SIMPLER diff --git a/pyaccuwage/fields.py b/pyaccuwage/fields.py index 2f0658e..655e464 100644 --- a/pyaccuwage/fields.py +++ b/pyaccuwage/fields.py @@ -62,6 +62,21 @@ class Field(object): 'dataLength': len(data) } + def fromJSON(self, o): + import re + + self.__init__( + name=o['name'], + max_length=o['maxLength'], + required=o['required'], + ) + + if isinstance(o['value'], basestring) and re.match('^\d*\.\d*$', o['value']): + o['value'] = decimal.Decimal(o['value']) + + self.value = o['value'] + return self + class TextField(Field): def validate(self): diff --git a/pyaccuwage/model.py b/pyaccuwage/model.py index 0a239a3..ed0884f 100644 --- a/pyaccuwage/model.py +++ b/pyaccuwage/model.py @@ -73,3 +73,22 @@ class Model(object): 'fields': self.get_sorted_fields() } + def fromJSON(self, o): + fields = o['fields'] + + for f in fields: + target = self.__dict__[f.name] + + if (target.required != f.required or + target.max_length != f.max_length): + print "Warning: value mismatch on import" + + target._value = f._value + + + #print (self.__dict__[f.name].name == f.name) + #self.__dict__[f.name].name == f.name + #self.__dict__[f.name].max_length == f.max_length + + return self +