Forked from
DM / dm-docs
261 commits behind, 8 commits ahead of the upstream repository.
Code owners
Assign users and groups as approvers for specific file changes. Learn more.
dmObject.py 2.42 KiB
#!/usr/bin/env python
#
# DM Object class.
#
#######################################################################
import UserDict
import UserList
import types
import json
from dm.common.exceptions.invalidArgument import InvalidArgument
from dm.common.utility import loggingManager
class DmObject(UserDict.UserDict):
""" Base dm object class. """
def __init__(self, dict={}):
if isinstance(dict, types.DictType):
UserDict.UserDict.__init__(self, dict)
elif isinstance(dict, UserDict.UserDict):
UserDict.UserDict.__init__(self, dict.data)
else:
raise InvalidArgument('DmObject must be initialized using dictionary.')
self._jsonPreprocessKeyList = []
self._logger = None
def getLogger(self):
if not self._logger:
self._logger = loggingManager.getLogger(self.__class__.__name__)
return self._logger
@classmethod
def getFromDict(cls, dict):
inst = cls()
for key in dict.keys():
inst[key] = dict[key]
return inst
def getDictRep(self):
# Dict representation is dict
dictRep = {}
for (key,obj) in self.data.items():
if isinstance(obj, DmObject):
dictRep[key] = obj.getDictRep()
else:
if obj is not None:
dictRep[key] = obj
return dictRep
def getDictJsonPreprocessedRep(self):
dictRep = self.getDictRep()
# Convert designated keys into string values.
for key in self._jsonPreprocessKeyList:
value = dictRep.get(key)
if value is not None:
dictRep[key] = '%s' % value
return dictRep
def getJsonRep(self):
dictRep = self.getDictJsonPreprocessedRep()
return json.dumps(dictRep)
@classmethod
def fromJsonString(cls, jsonString):
return cls.getFromDict(json.loads(jsonString))
#######################################################################
# Testing.
if __name__ == '__main__':
x = {'name' : 'XYZ', 'one':1, 'two':2 }
o = DmObject(x)
print 'DM Object: ', o
print 'Type of DM object: ', type(o)
print 'JSON Rep: ', o.getJsonRep()
print 'Type of JSON rep: ', type(o.getJsonRep())
j = '{"name" : "XYZ", "one":1, "two":2 }'
print 'String: ', j
x2 = DmObject.fromJsonString(j)
print 'DM Object 2: ', x2
print 'Type of DM object 2: ', type(x2)