How to use pika - 10 common examples

To help you get started, we’ve selected a few pika examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github pika / pika / tests / functional / test_async.py View on Github external
def _connect(self, connection_type):
        if self.connection:
            del self.connection
        self.connected = False
        parameters = pika.ConnectionParameters(HOST, PORT)
        return connection_type(parameters, self._on_connected)
github ManageIQ / integration_tests / cfme / utils / dockerbot / check_prs.py View on Github external
def send_message_to_bot(msg):

    required_fields = {'rabbitmq_url', 'gh_queue', 'gh_channel', 'gh_message_type'}
    if not required_fields.issubset(docker_conf.keys()):
        logger.warning(f"Skipping - docker.yaml doesn't have {required_fields}")
        return

    logger.info(f"Github PR bot: about to send '{msg}'")
    url = docker_conf['rabbitmq_url']
    queue = docker_conf['gh_queue']
    irc_channel = docker_conf['gh_channel']
#    message_type = docker_conf['gh_message_type']
    params = pika.URLParameters(url)
    params.socket_timeout = 5
    connection = None
    try:
        connection = pika.BlockingConnection(params)  # Connect to CloudAMQP
        channel = connection.channel()
        message = {"channel": irc_channel, "body": msg}
        channel.basic_publish(exchange='', routing_key=queue,
                              body=json.dumps(message, ensure_ascii=True))
    except Exception:
        output = traceback.format_exc()
        logger.warning(f"Exception while sending a message to the bot: {output}")
    finally:
        if connection:
            connection.close()
github carbonblack / cb-event-forwarder / tests / scripts / cbeventforwarder / bridge.py View on Github external
self.logger.info("processor_count (%s) > cpu_count. Defaulting to cpu_count", (processor_count, cpu_count))
            processor_count = cpu_count

        self.event_processor = EventProcessor(self.forwarder_options)
        self.processor_pool = multiprocessing.Pool(processor_count)

        while True:
            try:
                self.consume_message_bus(test=self.testing)
            except Exception as e:
                self.retry_attempts += 1
                if self.retry_attempts > self.max_retry_attempts:
                    self.logger.critical("Too many attempts to reconnect (%d). Exiting now." % self.max_retry_attempts)
                    break

                if isinstance(e, pika.exceptions.AMQPConnectionError) or isinstance(e, pika.exceptions.ConnectionClosed):
                    self.logger.error("Connection is closed or refused, retrying in %s seconds" % self.retry_interval)
                else:
                    self.logger.exception("An unexpected error occurred, retrying in %s seconds" % self.retry_interval)

                if self.connection is not None:
                    self.connection.close()
                    self.connection = None

                time.sleep(self.retry_interval)
github pika / pika / tests / unit / heartbeat_tests.py View on Github external
def test_connection_close(self):
        self.obj._idle_byte_intervals = 3
        self.obj._idle_heartbeat_intervals = 4
        self.obj._close_connection()
        reason = self.obj._STALE_CONNECTION % self.obj._timeout
        self.mock_conn._terminate_stream.assert_called_once_with(mock.ANY)

        self.assertIsInstance(self.mock_conn._terminate_stream.call_args[0][0],
                              pika.exceptions.AMQPHeartbeatTimeout)
        self.assertEqual(
            self.mock_conn._terminate_stream.call_args[0][0].args[0],
            reason)
github pika / pika / tests / unit / credentials_tests.py View on Github external
def test_ne(self):
        self.assertNotEqual(
            credentials.PlainCredentials('uu', 'p', False),
            credentials.PlainCredentials('u', 'p', False))

        self.assertNotEqual(
            credentials.PlainCredentials('u', 'p', False),
            credentials.PlainCredentials('uu', 'p', False))

        self.assertNotEqual(
            credentials.PlainCredentials('u', 'pp', False),
            credentials.PlainCredentials('u', 'p', False))

        self.assertNotEqual(
            credentials.PlainCredentials('u', 'p', False),
            credentials.PlainCredentials('u', 'pp', False))

        self.assertNotEqual(
            credentials.PlainCredentials('u', 'p', True),
            credentials.PlainCredentials('u', 'p', False))

        self.assertNotEqual(
            credentials.PlainCredentials('u', 'p', False),
            credentials.PlainCredentials('u', 'p', True))
github pika / pika / tests / unit / content_frame_assembler_tests.py View on Github external
def test_process_with_body_frame_partial(self):
        value = frame.Header(1, 100, spec.BasicProperties)
        self.obj.process(value)
        value = frame.Method(1, spec.Basic.Deliver())
        self.obj.process(value)
        value = frame.Body(1, b'abc123')
        self.obj.process(value)
        self.assertEqual(self.obj._body_fragments, [value.fragment])
github pika / pika / tests / unit / connection_tests.py View on Github external
def test_add_on_connection_unblocked_callback(self):
        unblocked_buffer = []
        self.connection.add_on_connection_unblocked_callback(
            lambda conn, frame: unblocked_buffer.append((conn, frame)))

        # Simulate dispatch of unblocked connection
        unblocked_frame = pika.frame.Method(0, pika.spec.Connection.Unblocked())
        self.connection._process_frame(unblocked_frame)

        self.assertEqual(len(unblocked_buffer), 1)
        conn, frame = unblocked_buffer[0]
        self.assertIs(conn, self.connection)
        self.assertIs(frame, unblocked_frame)
github pika / pika / tests / acceptance / twisted_adapter_tests.py View on Github external
def check(result):
            self.assertTrue(isinstance(result, Method))
            queue_obj.close.assert_called_once()
            self.assertTrue(isinstance(
                queue_obj.close.call_args[0][0], ConsumerCancelled))
            self.assertEqual(len(self.channel._consumers), 1)
            queue_obj_2.close.assert_not_called()
            self.assertEqual(
                self.channel._queue_name_to_consumer_tags["testqueue"],
                set())
        d.addCallback(check)
github pika / pika / tests / unit / channel_tests.py View on Github external
self.obj._cleanup = mock.Mock(wraps=self.obj._cleanup)

        # close() called by user
        self.obj.close(200, 'Got to go')

        self.obj._rpc.assert_called_once_with(
            spec.Channel.Close(200, 'Got to go', 0, 0), self.obj._on_closeok,
            [spec.Channel.CloseOk])

        self.assertEqual(self.obj._closing_reason.reply_code, 200)
        self.assertEqual(self.obj._closing_reason.reply_text, 'Got to go')
        self.assertEqual(self.obj._state, self.obj.CLOSING)

        # OpenOk method from broker
        self.obj._on_openok(
            frame.Method(self.obj.channel_number,
                         spec.Channel.OpenOk(self.obj.channel_number)))
        self.assertEqual(self.obj._state, self.obj.CLOSING)
        self.assertEqual(self.obj.callbacks.process.call_count, 0)

        # CloseOk method from broker
        self.obj._on_closeok(
            frame.Method(self.obj.channel_number, spec.Channel.CloseOk()))
        self.assertEqual(self.obj._state, self.obj.CLOSED)

        self.obj.callbacks.process.assert_any_call(self.obj.channel_number,
                                                   '_on_channel_close',
                                                   self.obj, self.obj,
                                                   mock.ANY)

        self.assertEqual(self.obj._cleanup.call_count, 1)
github pika / pika / tests / unit / channel_tests.py View on Github external
def test_on_flowok_callback_reset(self):
        method_frame = frame.Method(self.obj.channel_number,
                                    spec.Channel.FlowOk())
        mock_callback = mock.Mock()
        self.obj._on_flowok_callback = mock_callback
        self.obj._on_flowok(method_frame)
        self.assertIsNone(self.obj._on_flowok_callback)