def __init__(self, action, ec):
        if isinstance(action, dict):
            lazy_keys = []
            UserDict.__init__(self, action)
            if 'name' in self.data:
                self.data.setdefault('id', self.data['name'].lower())
                self.data.setdefault('title', self.data['name'])
                del self.data['name']
            self.data.setdefault('url', '')
            self.data.setdefault('link_target', None)
            self.data.setdefault('icon', '')
            self.data.setdefault('category', 'object')
            self.data.setdefault('visible', True)
            self.data['available'] = True
        else:
            # if action isn't a dict, it has to implement IAction
            (lazy_map, lazy_keys) = action.getInfoData()
            UserDict.__init__(self, lazy_map)

        self.data.setdefault('allowed', True)
        permissions = self.data.pop('permissions', ())
        if permissions:
            self.data['allowed'] = self._checkPermissions
            lazy_keys.append('allowed')

        self._ec = ec
        self._lazy_keys = lazy_keys
        self._permissions = permissions
示例#2
0
    def __init__(self, event_id, event_type, title, body,
                 timestamp=None, sender="", recipients=[],
                 tags=[], expiration_datetime=None, **kwargs):
        """Initialize event and default non-existing values."""
        if not event_id:
            event_id = str(uuid.uuid4())

        if not timestamp:
            timestamp = time.time()

        d = {"event_id": event_id,
             "event_type": event_type,
             "title": title,
             "body": body,
             "timestamp": timestamp,
             "sender": sender,
             "recipients": recipients,
             "tags": tags,
             "expiration_datetime": expiration_datetime}

        UserDict.__init__(self, dict=d, **kwargs)

        validator = Draft4Validator(Event.schema,
                                    types={"datetime": (datetime.datetime)},
                                    format_checker=FormatChecker())
        validator.validate(self.data)
    def __init__(self, action, ec):
        if isinstance(action, dict):
            lazy_keys = []
            UserDict.__init__(self, action)
            if 'name' in self.data:
                self.data.setdefault('id', self.data['name'].lower())
                self.data.setdefault('title', self.data['name'])
                del self.data['name']
            self.data.setdefault('url', '')
            self.data.setdefault('link_target', None)
            self.data.setdefault('icon', '')
            self.data.setdefault('category', 'object')
            self.data.setdefault('visible', True)
            self.data['available'] = True
        else:
            # if action isn't a dict, it has to implement IAction
            (lazy_map, lazy_keys) = action.getInfoData()
            UserDict.__init__(self, lazy_map)

        self.data.setdefault('allowed', True)
        permissions = self.data.pop('permissions', ())
        if permissions:
            self.data['allowed'] = self._checkPermissions
            lazy_keys.append('allowed')

        self._ec = ec
        self._lazy_keys = lazy_keys
        self._permissions = permissions
示例#4
0
 def __init__(self, name, label, handlerFn, validEvents, defaultArgs=None):
     UserDict.__init__(
         self, {
             "name": name,
             "label": label,
             "handlerFn": handlerFn,
             "validEvents": validEvents,
             "defaultArgs": defaultArgs
         })
示例#5
0
    def __init__(self, initial=None):
        handlers = initial or {
            'application/json': JSONHandler(),
            'application/json; charset=UTF-8': JSONHandler(),
        }

        # NOTE(jmvrbanac): Directly calling UserDict as it's not inheritable.
        # Also, this results in self.update(...) being called.
        UserDict.__init__(self, handlers)
示例#6
0
    def __init__(self, initial=None):
        handlers = initial or {
            'application/json': JSONHandler(),
            'application/json; charset=UTF-8': JSONHandler(),
        }

        # NOTE(jmvrbanac): Directly calling UserDict as it's not inheritable.
        # Also, this results in self.update(...) being called.
        UserDict.__init__(self, handlers)
示例#7
0
 def __init__(self, id, module, transform=None):
     self.id = id
     self.module = module
     # DM 2004-09-09: 'Transform' instances are stored as
     #  part of a module level configuration structure
     #  Therefore, they must not contain persistent objects
     self._config = UserDict()
     self._config.__allow_access_to_unprotected_subobjects__ = 1
     self._config_metadata = UserDict()
     self._tr_init(1, transform)
示例#8
0
 def __init__(self, dict=None):
     item = dict
     self._keys = []
     if isinstance(item, dict_alias):
         UserDict.__init__(self, item)
     else:
         UserDict.__init__(self, None)
     if isinstance(item, list):
         for (key, value) in item:
             self[key] = value
示例#9
0
 def __init__( self, dict=None ):
     item = dict
     self._keys = []
     if isinstance(item, dict_alias):
         UserDict.__init__( self, item )
     else:
         UserDict.__init__( self, None )
     if isinstance(item, list):
         for (key, value) in item:
             self[key] = value
示例#10
0
    def test_bobo_traverse_attribute_key_miss_R_M_default_real_request(self):
        from six.moves import UserDict
        request = UserDict()

        class _Response(object):
            def notFoundError(self, msg):
                1 / 0

        request.RESPONSE = _Response()
        app = self._makeOne()
        app._getOb = _noWay

        self.assertRaises(ZeroDivisionError,
                          app.__bobo_traverse__, request, 'NONESUCH')
示例#11
0
    def __init__(self, *args, **kwargs):
        IterableUserDict.__init__(self, *args, **kwargs)
        self.home = getenv('HOME')
        self.conf_file = self.get_configfile()

        if not path.isfile(self.conf_file):
            logging.error('Config-file %s missing. Using defaults.',
                          self.conf_file)
            self.use_defaults()
            # ensure parent directories exist.
            makedirs(path.dirname(self.conf_file))
            self.save()
        else:
            self.load()
示例#12
0
    def test_bobo_traverse_attribute_key_miss_R_M_default_real_request(self):
        from six.moves import UserDict
        request = UserDict()

        class _Response(object):
            def notFoundError(self, msg):
                1 / 0

        request.RESPONSE = _Response()
        app = self._makeOne()
        app._getOb = _noWay

        self.assertRaises(ZeroDivisionError, app.__bobo_traverse__, request,
                          'NONESUCH')
示例#13
0
    def __init__(self, row=()):
        UserDict.__init__(self)

        self['Satzart'] = self.satzart
        self._unmapped = []

        for i, value in enumerate(row):
            if (value is None
                    or isinstance(value, six.text_type) and value == ''):
                value = None
            try:
                field_name = self.fields[i]
            except IndexError:
                self._unmapped.append(value)
            else:
                self[field_name] = value
示例#14
0
    def update(self, other):
        try:
            # NOTE(kgriffs): If it is a mapping type, it should
            # implement keys().
            names = other.keys()
        except AttributeError:
            # NOTE(kgriffs): Not a mapping type, so assume it is an
            # iterable of 2-item iterables. But we need to make it
            # re-iterable if it is a generator, for when we pass
            # it on to the parent's update().
            other = list(other)
            names = [n for n, __ in other]

        for n in names:
            self._validate(n)

        UserDict.update(self, other)
示例#15
0
 def wrapped_context(self):
     """"We need to wrap the context to be able to acquire the root
         of the site to get tools, as done in plone.app.textfield"""
     context = self.context
     content = closest_content(context)
     if context.__class__ == dict:
         context = UserDict(self.context)
     return ImplicitAcquisitionWrapper(context, content)
示例#16
0
    def __init__(self,
                 event_id,
                 event_type,
                 title,
                 body,
                 timestamp=None,
                 sender="",
                 recipients=[],
                 tags=[],
                 expiration_datetime=None,
                 **kwargs):
        """Initialize event and default non-existing values."""
        if not event_id:
            event_id = str(uuid.uuid4())

        if not timestamp:
            timestamp = time.time()

        d = {
            "event_id": event_id,
            "event_type": event_type,
            "title": title,
            "body": body,
            "timestamp": timestamp,
            "sender": sender,
            "recipients": recipients,
            "tags": tags,
            "expiration_datetime": expiration_datetime
        }

        UserDict.__init__(self, dict=d, **kwargs)

        validator = Draft4Validator(Event.schema,
                                    types={"datetime": (datetime.datetime)},
                                    format_checker=FormatChecker())
        validator.validate(self.data)
示例#17
0
 def __setitem__(self, name, converter):
     self._validate(name)
     UserDict.__setitem__(self, name, converter)
示例#18
0
 def clear( self ):
     UserDict.clear( self )
     self._keys = []
示例#19
0
 def insert( self, index, key, item ):
     if key not in self._keys:
         self._keys.insert( index, key )
         UserDict.__setitem__( self, key, item )
 def copy(self):
     c = UserDict.copy(self)
     c._lazy_keys = self._lazy_keys[:]
     return c
示例#21
0
 def __delitem__( self, key ):
     UserDict.__delitem__( self, key )
     self._keys.remove( key )
示例#22
0
 def __init__(self,default=None):
   UserDict.__init__(self)
   for k,v in list((default or {}).items()):
     self[k]=v
 def __getitem__(self, key):
     value = UserDict.__getitem__(self, key)
     if key in self._lazy_keys:
         value = self.data[key] = value(self._ec)
         self._lazy_keys.remove(key)
     return value
示例#24
0
 def __init__(self,default=None):
   self._keys = {}
   UserDict.__init__(self,{})
   self.update(default or {})
示例#25
0
 def has_key(self,key):
   return UserDict.has_key(self,key.lower())
示例#26
0
 def pop(self, *args, **kwargs):
     try:
         return UserDict.pop(self, *args, **kwargs)
     finally:
         self.save()
示例#27
0
 def setdefault(self, key, failobj=None):
     if key not in self._keys:
         self._keys.append(key)
     return UserDict.setdefault(self, key, failobj)
示例#28
0
 def update(self, *args, **kwargs):
     UserDict.update(self, *args, **kwargs)
     self.save()
示例#29
0
 def __delitem__(self, *args, **kwargs):
     UserDict.__delitem__(self, *args, **kwargs)
     self.save()
示例#30
0
 def __init__(self, filepath):
     UserDict.__init__(self)
     self.synchronized_mutex = RLock()
     self.filepath = filepath
示例#31
0
    def test_dict_access_and_mod(self):
        """
        Test num dict access and modification
        """
        # dicts for testing
        dict_0 = {}  # Empty dictionary
        dict_1 = {1: 'Elephant'}  # Single numeric key
        dict_2 = {1: 'Elephant', 2: 'Mouse'}  # Multiple numeric keys

        #  Construct NumDicts from dicts
        num_dict_0 = NumDict()
        num_dict_1 = NumDict(dict_1)
        num_dict_2 = NumDict(dict_2)

        # test __getitem__
        self.assertEqual(num_dict_2[1], 'Elephant')
        with self.assertRaises(KeyError):
            _ = num_dict_1['Mouse']  # key is not numeric
        with self.assertRaises(KeyError):
            _ = num_dict_1.__getitem__('Mouse')  # key is not numeric
        with self.assertRaises(KeyError):
            _ = num_dict_1[None]  # key does not exist
        with self.assertRaises(KeyError):
            _ = num_dict_1.__getitem__(None)  # key does not exist

        # Test __setitem__
        num_dict_3 = NumDict(num_dict_2)
        self.assertEqual(num_dict_2, num_dict_3)

        num_dict_3[2] = 'Frog'
        self.assertNotEqual(num_dict_2, num_dict_3)

        # Check None keys and numeric key conversion
        num_dict_3['3'] = 'Armadillo'
        num_dict_3[None] = 'Cockroach'

        # Check long ints
        num_dict_3[12390809518259081208909880312] = 'Squid'
        num_dict_3['12390809518259081208909880312'] = 'Octopus'
        self.assertEqual(num_dict_3[12390809518259081208909880312], 'Octopus')

        with self.assertRaises(TypeError):
            num_dict_3.__setitem__('Gorilla', 1)  # key is not numeric
        with self.assertRaises(TypeError):
            num_dict_3['Chimpanzee'] = 1  # key is not numeric
        with self.assertRaises(TypeError):
            num_dict_3[(4, 1)] = 1  # key is not numeric
        with self.assertRaises(TypeError):
            num_dict_3[[1, 3, 4]] = 1  # key is not numeric and is not hashable

        # Test __delitem__
        del num_dict_3[3]
        del num_dict_3[None]
        with self.assertRaises(KeyError):
            del num_dict_3[3]  # already deleted
        with self.assertRaises(KeyError):
            num_dict_3.__delitem__(3)  # already deleted
        with self.assertRaises(KeyError):
            del num_dict_3[
                'Mouse']  # key would not exist, since it is not numeric

        # Test clear
        num_dict_3.clear()
        self.assertEqual(num_dict_3, {})

        # Test copy()
        num_dict_2a = dict_2.copy()
        self.assertEqual(num_dict_2, num_dict_2a)
        num_dict_2b = num_dict_2.copy()
        self.assertEqual(num_dict_2b, num_dict_2)
        num_dict_2c = UserDict({1: 'Elephant', 2: 'Mouse'})
        num_dict_2d = num_dict_2c.copy(
        )  # making a copy of a UserDict is special cased
        self.assertEqual(num_dict_2c, num_dict_2d)

        class MyNumDict(NumDict):
            """
            subclass Numdict for testing
            """
            def display(self):
                """
                add a method to subclass to differentiate from superclass
                """
                print('MyNumDict:', self)

        my_num_dict = MyNumDict(num_dict_2)
        my_num_dict_a = my_num_dict.copy()
        self.assertEqual(my_num_dict_a, my_num_dict)

        my_num_dict[1] = 'Frog'
        self.assertNotEqual(my_num_dict_a, my_num_dict)

        # Test keys, items, values
        self.assertEqual(sorted(six.iterkeys(num_dict_2)),
                         sorted(six.iterkeys(dict_2)))
        self.assertEqual(sorted(six.iteritems(num_dict_2)),
                         sorted(six.iteritems(dict_2)))
        self.assertEqual(sorted(six.itervalues(num_dict_2)),
                         sorted(six.itervalues(dict_2)))

        # Test "in".
        for i in num_dict_2:
            self.assertIn(i, num_dict_2)
            self.assertEqual(i in num_dict_1, i in dict_1)
            self.assertEqual(i in num_dict_0, i in dict_0)

        self.assertFalse(None in num_dict_2)
        self.assertEqual(None in num_dict_2, None in dict_2)

        dict_2[None] = 'Cow'
        num_dict_2[None] = dict_2[None]
        self.assertTrue(None in num_dict_2)
        self.assertEqual(None in num_dict_2, None in dict_2)

        self.assertFalse('Penguin' in num_dict_2)

        # Test update
        test = NumDict()
        test.update(dict_2)
        self.assertEqual(test, num_dict_2)

        # Test get
        for i in num_dict_2:
            self.assertEqual(num_dict_2.get(i), num_dict_2[i])
            self.assertEqual(num_dict_1.get(i), dict_1.get(i))
            self.assertEqual(num_dict_0.get(i), dict_0.get(i))

        for i in ['purple', None, 12312301924091284, 23]:
            self.assertEqual(num_dict_2.get(i), dict_2.get(i), i)

        with self.assertRaises(AssertionError):
            i = '1'
            self.assertEqual(
                num_dict_2.get(i), dict_2.get(i),
                i)  # dict_2 expects string key which does not exist

        # Test "in" iteration.
        num_dict_2b = num_dict_2
        for i in range(20):
            num_dict_2[i] = six.text_type(i)
            num_dict_2b[six.text_type(i)] = six.text_type(i)
        self.assertEqual(num_dict_2, num_dict_2b)

        ikeys = []
        for k in num_dict_2:
            ikeys.append(k)
        self.assertEqual(set(ikeys), set(num_dict_2.keys()))

        # Test setdefault
        val = 1
        test = NumDict()
        self.assertEqual(test.setdefault(val, 42), 42)
        self.assertEqual(test.setdefault(val, '42'), 42)
        self.assertNotEqual(test.setdefault(val, 42), '42')
        self.assertNotEqual(test.setdefault(val, '42'), '42')
        self.assertIn(val, test)

        self.assertEqual(test.setdefault(val, 23), 42)
        self.assertEqual(test.setdefault(val, '23'), 42)
        self.assertNotEqual(test.setdefault(val, 23), '42')
        self.assertNotEqual(test.setdefault(val, '23'), '42')
        self.assertIn(val, test)

        # Test pop
        val = 1
        test = NumDict({val: 42})
        self.assertEqual(test.pop(val), 42)
        self.assertRaises(KeyError, test.pop, val)
        self.assertEqual(test.pop(val, 1), 1)
        test[val] = 42
        self.assertEqual(test.pop(val, 1), 42)

        # Test popitem
        val = 1
        test = NumDict({val: 42})
        self.assertEqual(test.popitem(), (val, 42))
        self.assertRaises(KeyError, test.popitem)
示例#32
0
 def __init__(self, dict=None):
     self._keys = []
     UserDict.__init__(self, dict)
示例#33
0
 def insert(self, index, key, item):
     if key not in self._keys:
         self._keys.insert(index, key)
         UserDict.__setitem__(self, key, item)
示例#34
0
    def test_dict_access_and_mod(self):  # pylint: disable=too-many-locals, too-many-statements
        """
        Test num dict access and modification
        """
        # dicts for testing
        dict_0 = {}  # Empty dictionary
        dict_1 = {1: 'Elephant'}  # Single numeric key
        dict_2 = {1: 'Elephant', 2: 'Mouse'}  # Multiple numeric keys

        #  Construct NumDicts from dicts
        num_dict_0 = NumDict()
        num_dict_1 = NumDict(dict_1)
        num_dict_2 = NumDict(dict_2)

        # test __getitem__
        self.assertEqual(num_dict_2[1], 'Elephant')
        with self.assertRaises(KeyError):
            _ = num_dict_1['Mouse']  # key is not numeric
        with self.assertRaises(KeyError):
            _ = num_dict_1.__getitem__('Mouse')  # key is not numeric
        with self.assertRaises(KeyError):
            _ = num_dict_1[None]  # key does not exist
        with self.assertRaises(KeyError):
            _ = num_dict_1.__getitem__(None)  # key does not exist

        # Test __setitem__
        num_dict_3 = NumDict(num_dict_2)
        self.assertEqual(num_dict_2, num_dict_3)

        num_dict_3[2] = 'Frog'
        self.assertNotEqual(num_dict_2, num_dict_3)

        # Check None keys and numeric key conversion
        num_dict_3['3'] = 'Armadillo'
        num_dict_3[None] = 'Cockroach'

        # Check long ints
        num_dict_3[12390809518259081208909880312] = 'Squid'
        num_dict_3['12390809518259081208909880312'] = 'Octopus'
        self.assertEqual(num_dict_3[12390809518259081208909880312], 'Octopus')

        with self.assertRaises(TypeError):
            num_dict_3.__setitem__('Gorilla', 1)  # key is not numeric
        with self.assertRaises(TypeError):
            num_dict_3['Chimpanzee'] = 1  # key is not numeric
        with self.assertRaises(TypeError):
            num_dict_3[(4, 1)] = 1  # key is not numeric
        with self.assertRaises(TypeError):
            num_dict_3[[1, 3, 4]] = 1  # key is not numeric and is not hashable

        # Test __delitem__
        del num_dict_3[3]
        del num_dict_3[None]
        with self.assertRaises(KeyError):
            del num_dict_3[3]  # already deleted
        with self.assertRaises(KeyError):
            num_dict_3.__delitem__(3)  # already deleted
        with self.assertRaises(KeyError):
            del num_dict_3['Mouse']  # key would not exist, since it is not numeric

        # Test clear
        num_dict_3.clear()
        self.assertEqual(num_dict_3, {})

        # Test copy()
        num_dict_2a = dict_2.copy()
        self.assertEqual(num_dict_2, num_dict_2a)
        num_dict_2b = num_dict_2.copy()
        self.assertEqual(num_dict_2b, num_dict_2)
        num_dict_2c = UserDict({1: 'Elephant', 2: 'Mouse'})
        num_dict_2d = num_dict_2c.copy()  # making a copy of a UserDict is special cased
        self.assertEqual(num_dict_2c, num_dict_2d)

        class MyNumDict(NumDict):
            """
            subclass Numdict for testing
            """
            def display(self):
                """
                add a method to subclass to differentiate from superclass
                """
                print('MyNumDict:', self)

        my_num_dict = MyNumDict(num_dict_2)
        my_num_dict_a = my_num_dict.copy()
        self.assertEqual(my_num_dict_a, my_num_dict)

        my_num_dict[1] = 'Frog'
        self.assertNotEqual(my_num_dict_a, my_num_dict)

        # Test keys, items, values
        self.assertEqual(sorted(six.iterkeys(num_dict_2)), sorted(six.iterkeys(dict_2)))
        self.assertEqual(sorted(six.iteritems(num_dict_2)), sorted(six.iteritems(dict_2)))
        self.assertEqual(sorted(six.itervalues(num_dict_2)), sorted(six.itervalues(dict_2)))

        # Test "in".
        for i in num_dict_2:
            self.assertIn(i, num_dict_2)
            self.assertEqual(i in num_dict_1, i in dict_1)
            self.assertEqual(i in num_dict_0, i in dict_0)

        self.assertFalse(None in num_dict_2)
        self.assertEqual(None in num_dict_2, None in dict_2)

        dict_2[None] = 'Cow'
        num_dict_2[None] = dict_2[None]
        self.assertTrue(None in num_dict_2)
        self.assertEqual(None in num_dict_2, None in dict_2)

        self.assertFalse('Penguin' in num_dict_2)

        # Test update
        test = NumDict()
        test.update(dict_2)
        self.assertEqual(test, num_dict_2)

        # Test get
        for i in num_dict_2:
            self.assertEqual(num_dict_2.get(i), num_dict_2[i])
            self.assertEqual(num_dict_1.get(i), dict_1.get(i))
            self.assertEqual(num_dict_0.get(i), dict_0.get(i))

        for i in ['purple', None, 12312301924091284, 23]:
            self.assertEqual(num_dict_2.get(i), dict_2.get(i), i)

        with self.assertRaises(AssertionError):
            i = '1'
            self.assertEqual(num_dict_2.get(i), dict_2.get(i), i)  # dict_2 expects string key which does not exist

        # Test "in" iteration.
        num_dict_2b = num_dict_2
        for i in range(20):
            num_dict_2[i] = six.text_type(i)
            num_dict_2b[six.text_type(i)] = six.text_type(i)
        self.assertEqual(num_dict_2, num_dict_2b)

        ikeys = []
        for k in num_dict_2:
            ikeys.append(k)
        self.assertEqual(set(ikeys), set(num_dict_2.keys()))

        # Test setdefault
        val = 1
        test = NumDict()
        self.assertEqual(test.setdefault(val, 42), 42)
        self.assertEqual(test.setdefault(val, '42'), 42)
        self.assertNotEqual(test.setdefault(val, 42), '42')
        self.assertNotEqual(test.setdefault(val, '42'), '42')
        self.assertIn(val, test)

        self.assertEqual(test.setdefault(val, 23), 42)
        self.assertEqual(test.setdefault(val, '23'), 42)
        self.assertNotEqual(test.setdefault(val, 23), '42')
        self.assertNotEqual(test.setdefault(val, '23'), '42')
        self.assertIn(val, test)

        # Test pop
        val = 1
        test = NumDict({val: 42})
        self.assertEqual(test.pop(val), 42)
        self.assertRaises(KeyError, test.pop, val)
        self.assertEqual(test.pop(val, 1), 1)
        test[val] = 42
        self.assertEqual(test.pop(val, 1), 42)

        # Test popitem
        val = 1
        test = NumDict({val: 42})
        self.assertEqual(test.popitem(), (val, 42))
        self.assertRaises(KeyError, test.popitem)
 def copy(self):
     c = UserDict.copy(self)
     c._lazy_keys = self._lazy_keys[:]
     return c
示例#36
0
 def __new__(cls):
     return UserDict()
 def __getitem__(self, key):
     value = UserDict.__getitem__(self, key)
     if key in self._lazy_keys:
         value = self.data[key] = value(self._ec)
         self._lazy_keys.remove(key)
     return value
示例#38
0
class Transform(SimpleItem):
    """A transform is an external method with
    additional configuration information
    """

    meta_type = 'Transform'
    meta_types = all_meta_types = ()

    manage_options = ((
        {
            'label': 'Configure',
            'action': 'manage_main'
        },
        {
            'label': 'Reload',
            'action': 'manage_reloadTransform'
        },
    ) + SimpleItem.manage_options)

    manage_main = PageTemplateFile('configureTransform', _www)
    manage_reloadTransform = PageTemplateFile('reloadTransform', _www)
    tr_widgets = PageTemplateFile('tr_widgets', _www)

    security = ClassSecurityInfo()
    __allow_access_to_unprotected_subobjects__ = 1

    def __init__(self, id, module, transform=None):
        self.id = id
        self.module = module
        # DM 2004-09-09: 'Transform' instances are stored as
        #  part of a module level configuration structure
        #  Therefore, they must not contain persistent objects
        self._config = UserDict()
        self._config.__allow_access_to_unprotected_subobjects__ = 1
        self._config_metadata = UserDict()
        self._tr_init(1, transform)

    def __setstate__(self, state):
        """ __setstate__ is called whenever the instance is loaded
            from the ZODB, like when Zope is restarted.

            We should reload the wrapped transform at this time
        """
        Transform.inheritedAttribute('__setstate__')(self, state)
        self._tr_init()

    def _tr_init(self, set_conf=0, transform=None):
        """ initialize the zope transform by loading the wrapped transform """
        __traceback_info__ = (self.module, )
        if transform is None:
            transform = self._load_transform()
        else:
            self._v_transform = transform
        # check this is a valid transform
        if not hasattr(transform, '__class__'):
            raise TransformException(
                'Invalid transform : transform is not a class')
        if not ITransform.providedBy(transform):
            raise TransformException(
                'Invalid transform : ITransform is not implemented by %s' %
                transform.__class__)
        if not hasattr(transform, 'inputs'):
            raise TransformException(
                'Invalid transform : missing required "inputs" attribute')
        if not hasattr(transform, 'output'):
            raise TransformException(
                'Invalid transform : missing required "output" attribute')
        # manage configuration
        if set_conf and hasattr(transform, 'config'):
            conf = dict(transform.config)
            self._config.update(conf)
            make_config_persistent(self._config)
            if hasattr(transform, 'config_metadata'):
                conf = dict(transform.config_metadata)
                self._config_metadata.update(conf)
                make_config_persistent(self._config_metadata)
        transform.config = dict(self._config)
        make_config_nonpersistent(transform.config)
        transform.config_metadata = dict(self._config_metadata)
        make_config_nonpersistent(transform.config_metadata)

        self.inputs = transform.inputs
        self.output = transform.output
        self.output_encoding = getattr(transform, 'output_encoding', None)
        return transform

    def _load_transform(self):
        try:
            return self._v_transform
        except AttributeError:
            pass
        try:
            m = import_from_name(self.module)
        except ImportError as err:
            transform = BrokenTransform(self.id, self.module, err)
            msg = "Cannot register transform %s (ImportError), using BrokenTransform: Error\n %s" % (
                self.id, err)
            self.title = 'BROKEN'
            log(msg, severity=ERROR)
            return transform
        if not hasattr(m, 'register'):
            msg = 'Invalid transform module %s: no register function defined' % self.module
            raise TransformException(msg)
        try:
            transform = m.register()
        except Exception as err:
            transform = BrokenTransform(self.id, self.module, err)
            msg = "Cannot register transform %s, using BrokenTransform: Error\n %s" % (
                self.id, err)
            self.title = 'BROKEN'
            log(msg, severity=ERROR)
        else:
            self.title = ''
        self._v_transform = transform
        return transform

    security.declarePrivate('manage_beforeDelete')

    def manage_beforeDelete(self, item, container):
        SimpleItem.manage_beforeDelete(self, item, container)
        if self is item:
            # unregister self from catalog on deletion
            # While building business template, transform tool will be
            # copied and this transform will be removed from copied one
            # so that this must not use getToolByName to retrive the tool.
            tr_tool = self.aq_parent
            tr_tool._unmapTransform(self)

    security.declarePublic('get_documentation')

    def get_documentation(self):
        """ return transform documentation """
        return self._load_transform().__doc__

    security.declarePrivate('convert')

    def convert(self, *args, **kwargs):
        """ return apply the transform and return the result """
        return self._load_transform().convert(*args, **kwargs)

    security.declarePublic('name')

    def name(self):
        """return the name of the transform instance"""
        return self.id

    security.declareProtected(ManagePortal, 'get_parameters')

    def get_parameters(self):
        """ get transform's parameters names """
        return sorted(self._load_transform().config.keys())

    security.declareProtected(ManagePortal, 'get_parameter_value')

    def get_parameter_value(self, key):
        """ get value of a transform's parameter """
        value = self._config[key]
        type = self.get_parameter_infos(key)[0]
        if type == 'dict':
            result = {}
            for key, val in value.items():
                result[key] = val
        elif type == 'list':
            result = list(value)
        else:
            result = value
        return result

    security.declareProtected(ManagePortal, 'get_parameter_infos')

    def get_parameter_infos(self, key):
        """ get informations about a parameter

        return a tuple (type, label, description [, type specific data])
        where type in (string, int, list, dict)
              label and description are two string describing the field
        there may be some additional elements specific to the type :
             (key label, value label) for the dict type
        """
        try:
            return tuple(self._config_metadata[key])
        except KeyError:
            return 'string', '', ''

    security.declareProtected(ManagePortal, 'set_parameters')

    def set_parameters(self, REQUEST=None, **kwargs):
        """ set transform's parameters """
        if not kwargs:
            kwargs = REQUEST.form
        self.preprocess_param(kwargs)
        for param, value in kwargs.items():
            try:
                self.get_parameter_value(param)
            except KeyError:
                log('Warning: ignored parameter %r' % param)
                continue
            meta = self.get_parameter_infos(param)
            self._config[param] = VALIDATORS[meta[0]](value)

        tr_tool = getToolByName(self, 'portal_transforms')
        # need to remap transform if necessary (i.e. configurable inputs / output)
        if 'inputs' in kwargs or 'output' in kwargs:
            tr_tool._unmapTransform(self)
            transform = self._load_transform()
            self.inputs = kwargs.get('inputs', transform.inputs)
            self.output = kwargs.get('output', transform.output)
            tr_tool._mapTransform(self)
        # track output encoding
        if 'output_encoding' in kwargs:
            self.output_encoding = kwargs['output_encoding']
        if REQUEST is not None:
            REQUEST['RESPONSE'].redirect(tr_tool.absolute_url() +
                                         '/manage_main')

    security.declareProtected(ManagePortal, 'reload')

    def reload(self):
        """ reload the module where the transformation class is defined """
        log('Reloading transform %s' % self.module)
        if not self.module.startswith('erp5.'):
            reload(import_from_name(self.module))
        self._tr_init()

    security.declarePrivate('preprocess_param')

    def preprocess_param(self, kwargs):
        """ preprocess param fetched from an http post to handle optional dictionary
        """
        for param in self.get_parameters():
            if self.get_parameter_infos(param)[0] == 'dict':
                try:
                    keys = kwargs[param + '_key']
                    del kwargs[param + '_key']
                except:
                    keys = ()
                try:
                    values = kwargs[param + '_value']
                    del kwargs[param + '_value']
                except:
                    values = ()
                kwargs[param] = dict = {}
                for key, value in zip(keys, values):
                    key = key.strip()
                    if key:
                        value = value.strip()
                        if value:
                            dict[key] = value
示例#39
0
 def update(self, *args, **kwargs):
     if six.PY3:
         UserDict.update(self, *args, **kwargs)
     else:
         self._update_py2(*args, **kwargs)
示例#40
0
 def clear(self):
     UserDict.clear(self)
     self._keys = []
示例#41
0
 def __setitem__( self, key, item ):
     UserDict.__setitem__( self, key, item )
     if key not in self._keys:
         self._keys.append( key )
示例#42
0
 def __init__(self, *args, **kwargs):
     PdfType.__init__(self)
     UserDict.__init__(self, *args, **kwargs)
示例#43
0
 def setdefault( self, key, failobj=None ):
     if key not in self._keys:
         self._keys.append( key )
     return UserDict.setdefault( self, key, failobj )
示例#44
0
 def __init__(self, *args, **kwargs):
     UserDict.__init__(self, *args, **kwargs)
示例#45
0
 def set(self, key, value):
     UserDict.__setitem__(self, key, value)
示例#46
0
 def __copy__(self):
     return UserDict(self.data)
示例#47
0
from cinder.volume import qos_specs
from cinder.volume import utils as volutils
from cinder.volume import volume_types

test_volume = (UserDict({
    'name':
    'volume-728ec287-bf30-4d2d-98a8-7f1bed3f59ce',
    'volume_name':
    'test',
    'id':
    '728ec287-bf30-4d2d-98a8-7f1bed3f59ce',
    'volume_id':
    '728ec287-bf30-4d2d-98a8-7f1bed3f59ce',
    'provider_auth':
    None,
    'project_id':
    'project',
    'display_name':
    'test',
    'display_description':
    'test',
    'host':
    'controller@macrosan#MacroSAN',
    'size':
    10,
    'provider_location':
    'macrosan uuid:0x00b34201-025b0000-46b35ae7-b7deec47'
}))

test_volume.size = 10
test_volume.volume_type_id = None
test_volume.volume_attachment = []
示例#48
0
 def reset_config(self):
     """ Resets all to configuration to default state. """
     self.data = {}
     UserDict.__init__(self)
示例#49
0
def fun() -> Counter:
    return UserDict()
示例#50
0
    def __init__(self, ctx):
        UserDict.__init__(self)

        self._ctx = ctx