예제 #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))
예제 #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)
예제 #3
0
파일: message.py 프로젝트: fizyk/rabbitpy
    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))
예제 #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)
예제 #5
0
파일: base.py 프로젝트: datakurre/rabbitpy
    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
예제 #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
예제 #7
0
파일: base.py 프로젝트: fizyk/rabbitpy
    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
예제 #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)
예제 #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)
예제 #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)]
예제 #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)]
예제 #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
예제 #13
0
파일: message.py 프로젝트: boivie/rabbitpy
 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])
예제 #14
0
파일: message.py 프로젝트: cenk/rabbitpy
 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])
예제 #15
0
 def test_is_string_str(self):
     self.assertTrue(utils.is_string('Foo'))
예제 #16
0
 def test_is_string_bytes(self):
     self.assertTrue(utils.is_string(b'Foo'))
예제 #17
0
 def test_is_string_unicode(self):
     self.assertTrue(utils.is_string(unicode('Foo')))
예제 #18
0
 def test_is_string_false_int(self):
     self.assertFalse(utils.is_string(123))