Exemple #1
0
    def _as_datetime(self, value):
        """Return the passed in value as a ``datetime.datetime`` value.

        :param value: The value to convert or pass through
        :type value: datetime.datetime
        :type value: time.struct_time
        :type value: int
        :type value: float
        :type value: str
        :type value: bytes
        :type value: unicode
        :rtype: datetime.datetime
        :raises: TypeError

        """
        if value is None:
            return None

        if isinstance(value, datetime.datetime):
            return value

        if isinstance(value, time.struct_time):
            return datetime.datetime(*value[:6])

        if utils.is_string(value):
            value = int(value)

        if isinstance(value, float) or isinstance(value, int):
            return datetime.datetime.fromtimestamp(value)

        raise TypeError('Could not cast a %s value to a datetime.datetime' %
                        type(value))
Exemple #2
0
    def __setattr__(self, name, value):
        """Validate the data types for specific attributes when setting them,
        otherwise fall throw to the parent __setattr__

        :param str name: The attribute to set
        :param mixed value: The value to set
        :raises: ValueError

        """
        if value is not None:

            if (name in ['auto_delete', 'durable', 'exclusive'] and
                    not isinstance(value, bool)):
                raise ValueError('%s must be True or False' % name)

            if (name in ['max_length', 'message_ttl', 'expires'] and
                    not isinstance(value, int)):
                    raise ValueError('%s must be an int' % name)

            if (name in ['dead_letter_exchange', 'dead_letter_routing_key'] and
                    not utils.is_string(value)):
                    raise ValueError('%s must be a str, bytes or unicode' %
                                     name)

            if name == 'arguments' and not isinstance(value, dict):
                raise ValueError('arguments must be a dict')

        # Set the value
        super(Queue, self).__setattr__(name, value)
Exemple #3
0
    def _as_datetime(value):
        """Return the passed in value as a ``datetime.datetime`` value.

        :param value: The value to convert or pass through
        :type value: datetime.datetime
        :type value: time.struct_time
        :type value: int
        :type value: float
        :type value: str
        :type value: bytes
        :type value: unicode
        :rtype: datetime.datetime
        :raises: TypeError

        """
        if value is None:
            return None

        if isinstance(value, datetime.datetime):
            return value

        if isinstance(value, time.struct_time):
            return datetime.datetime(*value[:6])

        if utils.is_string(value):
            value = int(value)

        if isinstance(value, float) or isinstance(value, int):
            return datetime.datetime.fromtimestamp(value)

        raise TypeError('Could not cast a %s value to a datetime.datetime' %
                        type(value))
Exemple #4
0
    def __setattr__(self, name, value):
        """Validate the data types for specific attributes when setting them,
        otherwise fall throw to the parent __setattr__

        :param str name: The attribute to set
        :param mixed value: The value to set
        :raises: ValueError

        """
        if value is not None:

            if (name in ['auto_delete', 'durable', 'exclusive']
                    and not isinstance(value, bool)):
                raise ValueError('%s must be True or False' % name)

            if (name in ['max_length', 'message_ttl', 'expires']
                    and not isinstance(value, int)):
                raise ValueError('%s must be an int' % name)

            if (name in ['dead_letter_exchange', 'dead_letter_routing_key']
                    and not utils.is_string(value)):
                raise ValueError('%s must be a str, bytes or unicode' % name)

            if name == 'arguments' and not isinstance(value, dict):
                raise ValueError('arguments must be a dict')

        # Set the value
        super(Queue, self).__setattr__(name, value)
Exemple #5
0
    def __init__(self, channel, name):
        """Create a new ClassObject.

        :param rabbitpy.Channel channel: The channel to execute commands on
        :param str name: Set the name
        :raises: ValueError

        """
        # Use type so there's not a circular dependency
        if channel.__class__.__name__ != "Channel":
            raise ValueError("channel must be a valid rabbitpy Channel object")
        if not utils.is_string(name):
            raise ValueError("name must be str, bytes or unicode")

        self.channel = channel
        self.name = name
Exemple #6
0
    def __init__(self, channel, name):
        """Create a new ClassObject.

        :param rabbitpy.Channel channel: The channel to execute commands on
        :param str name: Set the name
        :raises: ValueError

        """
        # Use type so there's not a circular dependency
        if channel.__class__.__name__ != 'Channel':
            raise ValueError('channel must be a valid rabbitpy Channel object')
        if not utils.is_string(name):
            raise ValueError('name must be str, bytes or unicode')

        self.channel = channel
        self.name = name
Exemple #7
0
    def __init__(self, channel, name):
        """Create a new ClassObject.

        :param channel: The channel to execute commands on
        :type channel: rabbitpy.Channel
        :param str name: Set the name
        :raises: ValueError

        """
        super(AMQPClass, self).__init__(channel)
        # Use type so there's not a circular dependency
        if channel.__class__.__name__ != 'Channel':
            raise ValueError('channel must be a valid rabbitpy Channel object')
        elif not utils.is_string(name):
            raise ValueError('name must be str, bytes or unicode')
        self.name = name
Exemple #8
0
 def _coerce_properties(self):
     """Force properties to be set to the correct data type"""
     for key, value in self.properties.items():
         _type = getattr(specification.Basic.Properties, key)
         if _type == 'shortstr':
             if not utils.is_string(value):
                 LOGGER.warning('Coercing property %s to bytes', key)
                 value = str(value)
             self.properties[key] = utils.maybe_utf8_encode(value)
         elif _type == 'octet' and not isinstance(value, int):
             LOGGER.warning('Coercing property %s to int', key)
             self.properties[key] = int(value)
         elif _type == 'table' and not isinstance(value, dict):
             LOGGER.warning('Resetting invalid value for %s to None', key)
             self.properties[key] = {}
         if key == 'timestamp':
             self.properties[key] = self._as_datetime(value)
Exemple #9
0
 def _coerce_properties(self):
     """Force properties to be set to the correct data type"""
     for key, value in self.properties.items():
         _type = getattr(specification.Basic.Properties, key)
         if _type == 'shortstr':
             if not utils.is_string(value):
                 LOGGER.warning('Coercing property %s to bytes', key)
                 value = str(value)
             self.properties[key] = utils.maybe_utf8_encode(value)
         elif _type == 'octet' and not isinstance(value, int):
             LOGGER.warning('Coercing property %s to int', key)
             self.properties[key] = int(value)
         elif _type == 'table' and not isinstance(value, dict):
             LOGGER.warning('Resetting invalid value for %s to None', key)
             self.properties[key] = {}
         if key == 'timestamp':
             self.properties[key] = self._as_datetime(value)
Exemple #10
0
    def _normalize_expectations(channel_id, expectations):
        """Turn a class or list of classes into a list of class names.

        :param expectations: List of classes or class name or class obj
        :type expectations: list or str or pamqp.specification.Frame
        :rtype: list

        """
        if isinstance(expectations, list):
            output = list()
            for value in expectations:
                if isinstance(value, str):
                    output.append('%i:%s' % (channel_id, value))
                else:
                    output.append('%i:%s' % (channel_id, value.name))
            return output
        elif utils.is_string(expectations):
            return ['%i:%s' % (channel_id, expectations)]
        return ['%i:%s' % (channel_id, expectations.name)]
Exemple #11
0
    def _normalize_expectations(channel_id, expectations):
        """Turn a class or list of classes into a list of class names.

        :param expectations: List of classes or class name or class obj
        :type expectations: list or str or pamqp.specification.Frame
        :rtype: list

        """
        if isinstance(expectations, list):
            output = list()
            for value in expectations:
                if isinstance(value, str):
                    output.append('%i:%s' % (channel_id, value))
                else:
                    output.append('%i:%s' % (channel_id, value.name))
            return output
        elif utils.is_string(expectations):
            return ['%i:%s' % (channel_id, expectations)]
        return ['%i:%s' % (channel_id, expectations.name)]
Exemple #12
0
    def __init__(self, channel, name='',
                 durable=True, exclusive=False, auto_delete=False,
                 max_length=None, message_ttl=None, expires=None,
                 dead_letter_exchange=None, dead_letter_routing_key=None,
                 arguments=None):
        super(Queue, self).__init__(channel, name)

        # Validate Arguments
        for var, vname in [(auto_delete, 'auto_delete'), (durable, 'durable'),
                          (exclusive, 'exclusive')]:
            if not isinstance(var, bool):
                raise ValueError('%s must be True or False' % vname)

        for var, vname in [(max_length, 'max_length'),
                           (message_ttl, 'message_ttl'), (expires, 'expires')]:
            if var and not isinstance(var, int):
                raise ValueError('%s must be an int' % vname)

        for var, vname in [(dead_letter_exchange,
                            'dead_letter_exchange'),
                           (dead_letter_routing_key,
                            'dead_letter_routing_key')]:
            if var and not utils.is_string(var):
                raise ValueError('%s must be a str, bytes or unicode' % vname)

        if arguments and not isinstance(arguments, dict()):
            raise ValueError('arguments must be a dict')

        # Defaults
        self.consumer_tag = 'rabbitpy.%i.%s' % (self.channel.id, id(self))
        self.consuming = False

        # Assign Arguments
        self._durable = durable
        self._exclusive = exclusive
        self._auto_delete = auto_delete
        self._arguments = arguments or {}
        self._max_length = max_length
        self._message_ttl = message_ttl
        self._expires = expires
        self._dlx = dead_letter_exchange
        self._dlr = dead_letter_routing_key
Exemple #13
0
 def _coerce_properties(self):
     """Force properties to be set to the correct data type"""
     for key in self.properties:
         _type = getattr(specification.Basic.Properties, key)
         #LOGGER.debug('Type: %s, %s', _type, type(self.properties[key]))
         if _type == 'shortstr' and \
                 not utils.is_string(self.properties[key]):
             LOGGER.warning('Coercing property %s to bytes', key)
             self.properties[key] = bytes(self.properties[key])
         elif _type == 'octet' and not isinstance(self.properties[key],
                                                  int):
             LOGGER.warning('Coercing property %s to int', key)
             self.properties[key] = int(self.properties[key])
         elif _type == 'table' and not isinstance(self.properties[key],
                                                  dict):
             LOGGER.warning('Resetting invalid value for %s to None', key)
             self.properties[key] = {}
         elif _type == 'timestamp' and isinstance(self.properties[key],
                                                  int):
             LOGGER.warning('Coercing property %s to datetime', key)
             self.properties[key] = \
                 datetime.datetime.fromtimestamp(self.properties[key])
Exemple #14
0
 def _coerce_properties(self):
     """Force properties to be set to the correct data type"""
     for key in self.properties:
         _type = getattr(specification.Basic.Properties, key)
         #LOGGER.debug('Type: %s, %s', _type, type(self.properties[key]))
         if _type == 'shortstr' and \
                 not utils.is_string(self.properties[key]):
             LOGGER.warning('Coercing property %s to bytes', key)
             self.properties[key] = bytes(self.properties[key])
         elif _type == 'octet' and not isinstance(self.properties[key],
                                                  int):
             LOGGER.warning('Coercing property %s to int', key)
             self.properties[key] = int(self.properties[key])
         elif _type == 'table' and not isinstance(self.properties[key],
                                                  dict):
             LOGGER.warning('Resetting invalid value for %s to None', key)
             self.properties[key] = {}
         elif _type == 'timestamp' and isinstance(self.properties[key],
                                                  int):
             LOGGER.warning('Coercing property %s to datetime', key)
             self.properties[key] = \
                 datetime.datetime.fromtimestamp(self.properties[key])
Exemple #15
0
 def test_is_string_str(self):
     self.assertTrue(utils.is_string('Foo'))
Exemple #16
0
 def test_is_string_bytes(self):
     self.assertTrue(utils.is_string(b'Foo'))
Exemple #17
0
 def test_is_string_unicode(self):
     self.assertTrue(utils.is_string(unicode('Foo')))
Exemple #18
0
 def test_is_string_false_int(self):
     self.assertFalse(utils.is_string(123))