serialization_utils.py 11.8 KB
Newer Older
1
from import_dotnet import *
2 3
import time
import logging
4
logging.basicConfig(format='%(asctime)s %(message)s', level=logging.INFO)
5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278


#------------------------------supposed----------------------------------------
# Generic interfaces for pickling .net or standard objects
#------------------------------------------------------------------------------

#check if .net object and wrap it accordingly
def GetBaseOrLSO(obj):
    #print "----------------------------------------------------------------------------------"
    #print hasattr(obj, "GetType")
    if (hasattr(obj, "GetType")):
        #print System.Object().GetType().IsAssignableFrom(obj.GetType())
        #print "----------------------------------------------------------------------------------"
        if System.Object().GetType().IsAssignableFrom(obj.GetType()):
            try:
                srlz = Latino.ISerializable(obj)
                return LSO(srlz)
            except:
                return obj
        else:
            return obj
    else:
        #print "----------------------------------------------------------------------------------"
        return obj

#------------------------------supposed------------------------------------------------
# Generic interfaces for pickling .net objects
#------------------------------------------------------------------------------
class SerializableObject:
    netObj = None
    constructor = '<constructor_func_name>'
    def __init__(self, object = None):
        self.netObj = object
        self.copyAttributes()
    def createInstance(self, dict):
        constr = eval(self.constructor)
        args = self.getConstructorArgs(dict)
        self.netObj = constr(*args)
        self.copyAttributes()
    def getConstructorArgs(self, dict):
        if dict.has_key('constructorArgs'):
            return tuple([val for key,val in dict['constructorArgs'].items()])
        return ()
    def copyAttributes(self): #copy all attributes from wrapped object to the wrapper
        pass
        #for attr in dir(self.netObj):
        #    if hasattr(self.netObj, attr) and not hasattr(self, attr):
        #        setattr(self, attr, getattr(self.netObj, attr))
    def __repr__(self):
        #return "<" + self.netObj.__str__() + " wrapped in "+self.__class__.__name__+">"
        return "<" + self.netObj.__str__() + ">"
    def netObj(self):
        return self.netObj

class LatinoSerializableObject(SerializableObject):
    def __getstate__(self):
        logging.info('Serialize {0} with latino serializer (start)'.format(self.netObj.__class__.__name__))
        start = time.clock()
        byteData = LatinoCF.Save(self.netObj)
        elapsed = (time.clock() - start)
        logging.info('Serialize {0} with latino serializer (end, size: {1:,} chars) in {2} ms'.format(self.netObj.__class__.__name__, len(byteData),elapsed))
        return {'byteData': byteData}
    def __setstate__(self, dict):
        logging.info('Deserialize {0} with latino deserializer (start)'.format("<LatinoObject>"))
        start = time.clock()
        self.netObj = LatinoCF.Load(dict['byteData'])
        self.copyAttributes()
        elapsed = (time.clock() - start)
        logging.info('Deserialize {0} with latino deserializer (end, size: {1:,} chars) in {2} ms'.format(self.netObj.__class__.__name__, len(dict['byteData']),elapsed))
    def __repr__(self):
        return "<LSO: " + self.netObj.__str__() + ">"

LSO = LatinoSerializableObject

class ObjectFunctionSerializableObject(SerializableObject):
    save = '<save_data_func_name>'
    load = '<load_data_func_name>'
    def __getstate__(self):
        logging.info('Serialize {0} with obj.function {1} (start)'.format(self.__class__.__name__, self.save))
        saveFunc = getattr(self.netObj, self.save)
        data = saveFunc()
        logging.info('Serialize {0} with obj.function {1} (end, size: {2:,} chars)'.format(self.__class__.__name__, self.save, len(data)))
        return {'data': data}
    def __setstate__(self, dict):
        logging.info('Deserialize {0} with obj.function {1} (start)'.format(self.__class__.__name__, self.load))
        self.createInstance(dict)
        loadFunc = getattr(self.netObj, self.load)
        loadFunc(dict['data'])
        logging.info('Deserialize {0} with obj.function {1} (end, size: {2:,} chars)'.format(self.__class__.__name__, self.load, len(dict['data'])))

class ExternalFunctionSerializableObject(SerializableObject):
    save = '<save_data_func_name>'
    load = '<load_data_func_name>'
    def __getstate__(self):
        logging.info('Serialize {0} with ext.function {1} (start)'.format(self.__class__.__name__, self.save))
        saveFunc = eval(self.save)
        data = saveFunc(self.netObj)
        logging.info('Serialize {0} with ext.function {1} (end, size: {2:,} chars)'.format(self.__class__.__name__, self.save, len(data)))
        return {'data': data}
    def __setstate__(self, dict):
        logging.info('Deserialize {0} with ext.function {1} (start)'.format(self.__class__.__name__, self.load))
        loadFunc = eval(self.load)
        self.netObj = loadFunc(dict['data'])
        self.copyAttributes()
        logging.info('Deserialize {0} with ext.function {1} (end, size: {2:,} chars)'.format(self.__class__.__name__, self.load, len(dict['data'])))

class PropertySerializableObject(SerializableObject):
    constructorArgs = []
    props = []
    def __getstate__(self):
        logging.info('Serialize {0} properties (start)'.format(self.__class__.__name__))
        dictToSave = {'props':{},'constructorArgs':{}}
        for prop in self.props:
            if hasattr(self.netObj, prop):
                dictToSave['props'][prop] = getattr(self.netObj, prop)
        for constructorArg in self.constructorArgs:
            if hasattr(self.netObj, constructorArg):
                dictToSave['constructorArgs'][constructorArg] = getattr(self.netObj, constructorArg)
        logging.info('Serialize {0} properties (end {1:,} properties)'.format(self.__class__.__name__, len(dictToSave['props'])+len(dictToSave['constructorArgs'])))
        return dictToSave
    def __setstate__(self, dict):
        logging.info('Deserialize {0} properties (start)'.format(self.__class__.__name__))
        self.createInstance(dict)
        for prop in dict:
            if hasattr(self.netObj, prop):
                setattr(self.netObj, prop, dict[prop])
        logging.info('Deserialize {0} properties (end {1:,} properties)'.format(self.__class__.__name__, len(dict['props'])+len(dict['constructorArgs'])))

class ManuallySerializableObject(SerializableObject):
    def __getstate__(self):
        logging.info('Serialize {0} manually (start)'.format(self.__class__.__name__))
        dictToSave = self.getstate()
        logging.info('Serialize {0} manually ({1:,} properties)'.format(self.__class__.__name__, len(dictToSave)))
        return dictToSave
    def __setstate__(self, dict):
        logging.info('Deserialize {0} manually start)'.format(self.__class__.__name__))
        self.createInstance(dict)
        self.setstate(dict)
        logging.info('Deserialize {0} manually ({1:,} properties)'.format(self.__class__.__name__, len(dict)))
    def getstate(self):
        return {}
    def setstate(self, dict):
        pass

#------------------------------------------------------------------------------
# Helper functions
#------------------------------------------------------------------------------
def ToInt(s):
    try:
        return int(s)
    except:
        return 0
def ToFloat(s):
    try:
        return float(s)
    except:
        return 0
def ToBool(s):
    if s == 'true' or s == 'True':
        return True
    else:
        return False
def ToString(s):
    return s
def ToEnum(typ, s,defaultValue):
    return LatinoCF.ParseEnum[typ](s, defaultValue)
def ToIntList(s):
    il = []
    for i in s:
        il.append(ToInt(i))
    return il
def ToPyList(l):
    return [x for x in l]
def ToNetList(Type,l):
    a = System.Array[Type](l)
    return a
def IsSequence(arg):
    return (not hasattr(arg, "strip") and
            hasattr(arg, "__getitem__") or
            hasattr(arg, "__iter__"))
def Flatten(l, ltypes=(list, tuple)):
    ltype = type(l)
    l = list(l)
    i = 0
    while i < len(l):
        while isinstance(l[i], ltypes):
            if not l[i]:
                l.pop(i)
                i -= 1
                break
            else:
                l[i:i + 1] = l[i]
        i += 1
    return ltype(l)

def ToNetObj(data):
    if hasattr(data, "netObj"):
        return data.netObj
    if isinstance(data, dict):
        if not len(data):
            return System.Collections.Generic.Dictionary[System.Object,System.Object]()
        else:
            key = ToNetObj(data.keys()[0])
            val = ToNetObj(data.values()[0])
            for tryIndex in [0, 1]:
                try:
                    if not tryIndex:
                        d = System.Collections.Generic.Dictionary[type(key),type(val)]()
                    else:
                        d = System.Collections.Generic.Dictionary[System.Object,System.Object]()
                    for key,val in data.items():
                        k = ToNetObj(key)
                        v = ToNetObj(val)
                        d[k] = v
                    return d
                except:
                    pass
            return System.Object()
    if isinstance(data, list):
        if not len(data):
            return System.Collections.Generic.List[System.Object]()
        else:
            dataNet = ToNetObj(data[0])
            for tryIndex in [0, 1]:
                try:
                    if not tryIndex:
                        l = System.Collections.Generic.List[type(dataNet)]()
                    else:
                        l = System.Collections.Generic.List[System.Object]()
                    for i, val in enumerate(data):
                        l.Add(ToNetObj(val))
                    return l
                except:
                    pass
            return System.Object()
    if isinstance(data, tuple):
        if not len(data):
            return System.Collections.Generic.LinkedList[System.Object]()
        else:
            dataNet = ToNetObj(data[0])
            for tryIndex in [0, 1]:
                try:
                    if not tryIndex:
                        a = System.Collections.Generic.LinkedList[type(dataNet)]()
                    else:
                        a = System.Collections.Generic.LinkedList[System.Object]()
                    for i, val in enumerate(data):
                        a.AddLast(ToNetObj(val))
                    return a
                except:
                    pass
            return System.Object()
    return data
def ToPyObj(data):
    if hasattr(data, "GetType") and data.GetType().IsGenericType:
        genType = data.GetType().GetGenericTypeDefinition()
        if genType.Equals(System.Collections.Generic.Dictionary):
            d = {}
            for keyVal in data:
                k = ToPyObj(keyVal.Key)
                v = ToPyObj(keyVal.Value)
                d[k] = v
            return d
        if genType.Equals(System.Collections.Generic.List):
            l = []
            for val in data:
                l.append(ToPyObj(val))
            return l
        if genType.Equals(System.Collections.Generic.LinkedList):
            l = []
            for val in data:
                l.append(ToPyObj(val))
            return tuple(l)
    if hasattr(data, "GetType"):
279 280 281 282
        type = data.GetType()
        if type.IsArray:
            return [ToPyObj(x) for x in data]
        for interface in type.GetInterfaces():
283 284 285
            if interface.Name == u'ISerializable':
                return LSO(data)
    return data