Ejemplo n.º 1
0
class CachedUUIDObjectJSON(ObjectJSON):
    def __init__(self, unit_system=None):
        super(CachedUUIDObjectJSON, self).__init__(unit_system)
        self.excluded_keys = ['json']
        self.uuid_cache = WeakValueCache()

    def simplify(self, obj, base_type=''):
        if obj.__class__.__module__ != '__builtin__':
            if hasattr(obj, 'to_dict') and hasattr(obj, '__uuid__'):
                # the object knows how to dismantle itself into a json string
                if obj.__uuid__ not in self.uuid_cache:
                    self.uuid_cache[obj.__uuid__] = obj

                    return {
                        '_cls': obj.__class__.__name__,
                        '_obj_uuid': str(obj.__uuid__),
                        '_dict': self.simplify(obj.to_dict(), base_type)}
                else:
                    return {
                        '_obj_uuid': str(obj.__uuid__)}

        return super(CachedUUIDObjectJSON, self).simplify(obj, base_type)

    def build(self, jsn):
        if type(jsn) is dict:
            if '_obj_uuid' in jsn:
                uuid = UUID(jsn['_obj_uuid'])
                if uuid in self.uuid_cache:
                    return self.uuid_cache[uuid]
                elif '_cls' in jsn and '_dict' in jsn:
                    if jsn['_cls'] not in self.class_list:
                        self.update_class_list()
                        if jsn['_cls'] not in self.class_list:
                            raise ValueError((
                                 'Cannot create jsn of class `%s`.\n' +
                                 'Class is not registered as creatable! '
                                 'You might have to define\n' +
                                 'the class locally and call '
                                 '`update_storable_classes()` on your storage.') %
                             jsn['_cls'])

                    attributes = self.build(jsn['_dict'])

                    obj = self.class_list[jsn['_cls']].from_dict(attributes)
                    obj.__uuid__ = uuid
                    self.uuid_cache[uuid] = obj
                    return obj
                else:
                    # this should not happen!
                    raise ('What happend here. JSN `%s`' % jsn)
                    pass

        return super(CachedUUIDObjectJSON, self).build(jsn)

    def to_json(self, obj, base_type=''):
        # we need to clear the cache, since we have no idea, what the other end
        # still knows. We can only cache stuff we are sending this time
        self.uuid_cache.clear()
        return super(CachedUUIDObjectJSON, self).to_json(obj, base_type)
Ejemplo n.º 2
0
 def __init__(self, unit_system=None):
     super(CachedUUIDObjectJSON, self).__init__(unit_system)
     self.excluded_keys = ['json']
     self.uuid_cache = WeakValueCache()