示例#1
0
    def publish(self, exchange, routing_key='', mandatory=False):
        """Publish the message to the exchange with the specified routing
        key.

        In Python 2 if the message is a ``unicode`` value it will be converted
        to a ``str`` using ``str.encode('UTF-8')``. If you do not want the
        auto-conversion to take place, set the body to a ``str`` or ``bytes``
        value prior to publishing.

        In Python 3 if the message is a ``str`` value it will be converted to
        a ``bytes`` value using ``bytes(value.encode('UTF-8'))``. If you do
        not want the auto-conversion to take place, set the body to a
        ``bytes`` value prior to publishing.

        :param exchange: The exchange to publish the message to
        :type exchange: str or :class:`rabbitpy.Exchange`
        :param str routing_key: The routing key to use
        :param bool mandatory: Requires the message is published
        :return: bool or None
        :raises: rabbitpy.exceptions.MessageReturnedException

        """
        if isinstance(exchange, base.AMQPClass):
            exchange = exchange.name

        # Coerce the body to the proper type
        payload = utils.maybe_utf8_encode(self.body)

        frames = [
            specification.Basic.Publish(exchange=exchange,
                                        routing_key=routing_key or '',
                                        mandatory=mandatory),
            header.ContentHeader(body_size=len(payload),
                                 properties=self._properties)
        ]

        # Calculate how many body frames are needed
        pieces = int(
            math.ceil(len(payload) / float(self.channel.maximum_frame_size)))

        # Send the message
        for offset in range(0, pieces):
            start = self.channel.maximum_frame_size * offset
            end = start + self.channel.maximum_frame_size
            if end > len(payload):
                end = len(payload)
            frames.append(body.ContentBody(payload[start:end]))

        # Write the frames out
        self.channel._write_frames(frames)

        # If publisher confirmations are enabled, wait for the response
        if self.channel.publisher_confirms:
            response = self.channel._wait_for_confirmation()
            if isinstance(response, specification.Basic.Ack):
                return True
            elif isinstance(response, specification.Basic.Nack):
                return False
            else:
                raise exceptions.UnexpectedResponseError(response)
示例#2
0
    def publish(self, exchange, routing_key='', mandatory=False):
        """Publish the message to the exchange with the specified routing
        key.

        In Python 2 if the message is a ``unicode`` value it will be converted
        to a ``str`` using ``str.encode('UTF-8')``. If you do not want the
        auto-conversion to take place, set the body to a ``str`` or ``bytes``
        value prior to publishing.

        In Python 3 if the message is a ``str`` value it will be converted to
        a ``bytes`` value using ``bytes(value.encode('UTF-8'))``. If you do
        not want the auto-conversion to take place, set the body to a
        ``bytes`` value prior to publishing.

        :param exchange: The exchange to publish the message to
        :type exchange: str or :class:`rabbitpy.Exchange`
        :param str routing_key: The routing key to use
        :param bool mandatory: Requires the message is published
        :return: bool or None
        :raises: rabbitpy.exceptions.MessageReturnedException

        """
        if isinstance(exchange, base.AMQPClass):
            exchange = exchange.name

        # Coerce the body to the proper type
        payload = utils.maybe_utf8_encode(self.body)

        frames = [specification.Basic.Publish(exchange=exchange,
                                              routing_key=routing_key or '',
                                              mandatory=mandatory),
                  header.ContentHeader(body_size=len(payload),
                                       properties=self._properties)]

        # Calculate how many body frames are needed
        pieces = int(math.ceil(len(payload) /
                               float(self.channel.maximum_frame_size)))

        # Send the message
        for offset in range(0, pieces):
            start = self.channel.maximum_frame_size * offset
            end = start + self.channel.maximum_frame_size
            if end > len(payload):
                end = len(payload)
            frames.append(body.ContentBody(payload[start:end]))

        # Write the frames out
        self.channel._write_frames(frames)

        # If publisher confirmations are enabled, wait for the response
        if self.channel.publisher_confirms:
            response = self.channel._wait_for_confirmation()
            if isinstance(response, specification.Basic.Ack):
                return True
            elif isinstance(response, specification.Basic.Nack):
                return False
            else:
                raise exceptions.UnexpectedResponseError(response)
示例#3
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)
示例#4
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)