### Install rabbitpy Source: https://gmr.github.io/rabbitpy Install the rabbitpy library using pip. This is the first step before using the library. ```bash pip install rabbitpy ``` -------------------------------- ### Example Usage of Exception Handling Source: https://gmr.github.io/rabbitpy/api/exceptions Demonstrates how to catch specific rabbitpy exceptions, such as AMQPPreconditionFailed, when interacting with RabbitMQ. ```APIDOC ## Example Usage of Exception Handling This example shows how to use a try-except block to catch `rabbitpy.exceptions.AMQPPreconditionFailed` when declaring a queue with conflicting parameters. ### Code Example ```python import rabbitpy try: with rabbitpy.Connection() as connection: with connection.channel() as channel: queue = rabbitpy.Queue(channel, 'exception-test') queue.durable = True queue.declare() queue.durable = False queue.declare() # raises AMQPPreconditionFailed except rabbitpy.exceptions.AMQPPreconditionFailed: print('Queue already exists with different parameters') ``` ``` -------------------------------- ### Custom Connection URI Example Source: https://gmr.github.io/rabbitpy/api/connection Connect to a specific virtual host ('test') on a remote RabbitMQ server with custom user credentials and host/port. ```plaintext :code:`amqp://www:rabbitmq@192.168.1.200:5672/test` ``` -------------------------------- ### Get Messages One by One from Queue Source: https://gmr.github.io/rabbitpy/examples/getter Use this to retrieve messages from a queue until it is empty. It checks the queue length before each retrieval and acknowledges each message. ```python #!/usr/bin/env python import rabbitpy with rabbitpy.Connection('amqp://guest:guest@localhost:5672/%2f') as conn: with conn.channel() as channel: queue = rabbitpy.Queue(channel, 'example') while len(queue) > 0: message = queue.get() message.pprint(True) message.ack() print(f'There are {len(queue)} more messages in the queue') ``` -------------------------------- ### Consume Messages from a Queue Source: https://gmr.github.io/rabbitpy/examples/consumer Subscribes to the 'test' queue and consumes messages until interrupted. Ensure you have a running RabbitMQ instance and the rabbitpy library installed. ```python #!/usr/bin/env python import logging import rabbitpy URL = 'amqp://guest:guest@localhost:5672/%2f?heartbeat=15' logging.basicConfig(level=logging.INFO) with rabbitpy.Connection(URL) as conn: with conn.channel() as channel: try: for message in rabbitpy.Queue(channel, 'test'): message.pprint(True) message.ack() except KeyboardInterrupt: logging.info('Exited consumer') ``` -------------------------------- ### RabbitMQ Connection URL Syntax Source: https://gmr.github.io/rabbitpy/api/connection Illustrates the standard AMQP URI syntax for specifying connection details, including optional user, password, host, port, virtual host, and query parameters. ```plaintext amqp[s]://[user:password@]host[:port]/[vhost][?key=value...] ``` -------------------------------- ### Connection Methods Source: https://gmr.github.io/rabbitpy/api/connection Methods for managing the connection lifecycle and creating channels. ```APIDOC ## Connection Methods ### `__enter__()` For use as a context manager, return a handle to this object instance. ### `__exit__(exc_type, exc_val, unused_exc_tb)` Close the connection when the context exits. ### `channel(blocking_read=False)` Create and return a new AMQP channel. * `blocking_read` (bool): Enable blocking reads for higher throughput. Defaults to `False`. ### `close()` Close the connection to RabbitMQ, including all open channels. ### `connect()` Connect to RabbitMQ and negotiate the AMQP connection. ``` -------------------------------- ### Create and Close a RabbitMQ Connection Source: https://gmr.github.io/rabbitpy/api/connection Instantiate a Connection object with an AMQP URI and explicitly close it when done. ```python conn = rabbitpy.Connection('amqp://guest:guest@localhost:5672/%2F') conn.close() ``` -------------------------------- ### Connect and Publish a Message with rabbitpy Source: https://gmr.github.io/rabbitpy Connect to a RabbitMQ instance and publish a message to an exchange with a routing key. Ensure a RabbitMQ server is running and accessible at the specified URL. ```python import rabbitpy with rabbitpy.Connection('amqp://guest:guest@localhost:5672/%2f') as conn: with conn.channel() as channel: message = rabbitpy.Message(channel, 'Hello, RabbitMQ!') message.publish('my-exchange', 'routing-key') ``` -------------------------------- ### Multi-threaded RabbitMQ Publisher and Consumer Source: https://gmr.github.io/rabbitpy/threads Connect to RabbitMQ and spawn separate threads for publishing and consuming messages. Ensure each channel is used by only one thread. ```python import rabbitpy import threading EXCHANGE = 'threading_example' QUEUE = 'threading_queue' ROUTING_KEY = 'test' MESSAGE_COUNT = 100 def consumer(connection): """Consume MESSAGE_COUNT messages then exit.""" received = 0 with connection.channel() as channel: for message in rabbitpy.Queue(channel, QUEUE): print(message.body) message.ack() received += 1 if received == MESSAGE_COUNT: break def publisher(connection): """Publish MESSAGE_COUNT messages.""" with connection.channel() as channel: for index in range(MESSAGE_COUNT): message = rabbitpy.Message(channel, f'Message #{index}') message.publish(EXCHANGE, ROUTING_KEY) with rabbitpy.Connection() as connection: with connection.channel() as channel: exchange = rabbitpy.Exchange(channel, EXCHANGE) exchange.declare() queue = rabbitpy.Queue(channel, QUEUE) queue.declare() queue.bind(EXCHANGE, ROUTING_KEY) kwargs = {'connection': connection} consumer_thread = threading.Thread(target=consumer, kwargs=kwargs) consumer_thread.start() publisher_thread = threading.Thread(target=publisher, kwargs=kwargs) publisher_thread.start() consumer_thread.join() ``` -------------------------------- ### AMQPNotImplemented Source: https://gmr.github.io/rabbitpy/api/exceptions Raised when the client tries to use functionality that is not implemented in the server. ```APIDOC ## `rabbitpy.exceptions.AMQPNotImplemented` ### Description The client tried to use functionality that is not implemented in the server. ### Bases `AMQPException` ``` -------------------------------- ### AMQPNoRoute Source: https://gmr.github.io/rabbitpy/api/exceptions Undocumented AMQP Soft Error. ```APIDOC ## `rabbitpy.exceptions.AMQPNoRoute` ### Description Undocumented AMQP Soft Error ### Bases `AMQPException` ``` -------------------------------- ### Publish Message to Exchange Source: https://gmr.github.io/rabbitpy/examples/publisher Connects to a RabbitMQ instance, declares an exchange, creates a message with custom properties including a timestamp and message ID, and publishes it to the specified exchange with a routing key. Ensure RabbitMQ is running and accessible at the specified connection string. ```python #!/usr/bin/env python import datetime import uuid import rabbitpy with rabbitpy.Connection('amqp://guest:guest@localhost:5672/%2f') as conn: with conn.channel() as channel: exchange = rabbitpy.Exchange(channel, 'example_exchange') exchange.declare() message = rabbitpy.Message( channel, 'Lorem ipsum dolor sit amet, consectetur adipiscing elit.', { 'content_type': 'text/plain', 'delivery_mode': 1, 'message_type': 'Lorem ipsum', 'timestamp': datetime.datetime.now(tz=datetime.UTC), 'message_id': str(uuid.uuid4()), }, ) message.publish(exchange, 'test-routing-key') ``` -------------------------------- ### Handling AMQPPreconditionFailed Exception Source: https://gmr.github.io/rabbitpy/api/exceptions Demonstrates how to catch and handle the AMQPPreconditionFailed exception, which can occur when declaring a queue with parameters that conflict with an existing queue. ```python import rabbitpy try: with rabbitpy.Connection() as connection: with connection.channel() as channel: queue = rabbitpy.Queue(channel, 'exception-test') queue.durable = True queue.declare() queue.durable = False queue.declare() # raises AMQPPreconditionFailed except rabbitpy.exceptions.AMQPPreconditionFailed: print('Queue already exists with different parameters') ``` -------------------------------- ### Consume Messages with rabbitpy Source: https://gmr.github.io/rabbitpy Connect to a RabbitMQ instance, declare a queue, and consume messages from it. Messages are printed to the console and acknowledged. Ensure the queue exists or is created by the consumer. ```python import rabbitpy with rabbitpy.Connection('amqp://guest:guest@localhost:5672/%2f') as conn: with conn.channel() as channel: queue = rabbitpy.Queue(channel, 'my-queue') for message in queue: print(message.body) message.ack() ``` -------------------------------- ### Default Connection URI Source: https://gmr.github.io/rabbitpy/api/connection The default AMQP URL used when no URL is provided to the Connection constructor. It specifies localhost, port 5672, virtual host '/', and guest/guest credentials. ```plaintext :code:`amqp://guest:guest@localhost:5672/%2F` ``` -------------------------------- ### Connection Properties Source: https://gmr.github.io/rabbitpy/api/connection Properties available on the Connection object to inspect its state and capabilities. ```APIDOC ## Connection Properties ### `args` property Return the connection arguments. ### `blocked` property Indicates if the connection is blocked from publishing by RabbitMQ. ### `capabilities` property Return the RabbitMQ server capabilities from negotiation. ### `server_properties` property Return the RabbitMQ server properties from negotiation. ``` -------------------------------- ### AMQPNotFound Source: https://gmr.github.io/rabbitpy/api/exceptions Raised when the client attempts to work with a server entity that does not exist. ```APIDOC ## `rabbitpy.exceptions.AMQPNotFound` ### Description The client attempted to work with a server entity that does not exist. ### Bases `AMQPException` ``` -------------------------------- ### Create a New AMQP Channel Source: https://gmr.github.io/rabbitpy/api/connection Obtain a new AMQP channel from an existing connection. The `blocking_read` parameter can be set to `True` to enable blocking reads for potentially higher throughput, though it may affect interrupt handling. ```python channel(blocking_read=False) ``` -------------------------------- ### rabbitpy.exceptions.NotSupportedError Source: https://gmr.github.io/rabbitpy/api/exceptions Raised when a requested feature is not supported by the connected RabbitMQ server. ```APIDOC ## rabbitpy.exceptions.NotSupportedError Bases: `RabbitpyException` Raised when a feature is requested that is not supported by the RabbitMQ server. ``` -------------------------------- ### AMQPInvalidPath Source: https://gmr.github.io/rabbitpy/api/exceptions Raised when the client tries to work with an unknown virtual host. ```APIDOC ## `rabbitpy.exceptions.AMQPInvalidPath` ### Description The client tried to work with an unknown virtual host. ### Bases `AMQPException` ``` -------------------------------- ### AMQPResourceError Source: https://gmr.github.io/rabbitpy/api/exceptions Raised when the server cannot complete a method due to insufficient resources, possibly caused by the client creating too many entities. ```APIDOC ## `rabbitpy.exceptions.AMQPResourceError` ### Description The server could not complete the method because it lacked sufficient resources. This may be due to the client creating too many of some type of entity. ### Bases `AMQPException` ``` -------------------------------- ### rabbitpy.exceptions.AMQPAccessRefused Source: https://gmr.github.io/rabbitpy/api/exceptions Raised when a client attempts to access a server entity to which it lacks permissions due to security settings. ```APIDOC ## rabbitpy.exceptions.AMQPAccessRefused Bases: `AMQPException` The client attempted to work with a server entity to which it has no access due to security settings. ``` -------------------------------- ### rabbitpy.exceptions.AMQPException Source: https://gmr.github.io/rabbitpy/api/exceptions The base exception class for all AMQP-related exceptions. ```APIDOC ## rabbitpy.exceptions.AMQPException Bases: `RabbitpyException` Base exception for all AMQP exceptions. ``` -------------------------------- ### AMQPPreconditionFailed Source: https://gmr.github.io/rabbitpy/api/exceptions Raised when the client requests a method that was not allowed because some precondition failed. ```APIDOC ## `rabbitpy.exceptions.AMQPPreconditionFailed` ### Description The client requested a method that was not allowed because some precondition failed. ### Bases `AMQPException` ``` -------------------------------- ### rabbitpy.connection.Connection Source: https://gmr.github.io/rabbitpy/api/connection The Connection object is responsible for negotiating a connection and managing its state. It can be initialized with an AMQP URL or default parameters. ```APIDOC ## rabbitpy.connection.Connection ### Description The Connection object is responsible for negotiating a connection and managing its state. When creating a new instance of the Connection object, if no URL is passed in, it uses the default connection parameters of localhost port 5672, virtual host / with the guest/guest username/password combination. ### Parameters * `url` (str): The AMQP connection URL. * `connection_name` (str, optional): An optional name for the connection. * `client_properties` (dict, optional): Optional client properties to send. ### Raises * exceptions.AMQPException * exceptions.ConnectionException * exceptions.ConnectionResetException * exceptions.RemoteClosedException ``` -------------------------------- ### rabbitpy.exceptions.ConnectionException Source: https://gmr.github.io/rabbitpy/api/exceptions Raised when rabbitpy fails to establish a connection to the specified server, particularly if the RabbitMQ version does not support `authentication_failure_close`. ```APIDOC ## rabbitpy.exceptions.ConnectionException Bases: `RabbitpyException` Raised when Rabbitpy can not connect to the specified server and if a connection fails and the RabbitMQ version does not support the authentication_failure_close feature added in RabbitMQ 3.2. ``` -------------------------------- ### Use RabbitMQ Connection as a Context Manager Source: https://gmr.github.io/rabbitpy/api/connection Utilize the Connection object as a context manager for automatic connection closing. This ensures the connection is properly closed when exiting the 'with' block. ```python with rabbitpy.Connection() as conn: with conn.channel() as channel: # use channel pass ``` -------------------------------- ### AMQPContentTooLarge Source: https://gmr.github.io/rabbitpy/api/exceptions Raised when the client attempts to transfer content larger than the server can accept. The client may retry at a later time. ```APIDOC ## `rabbitpy.exceptions.AMQPContentTooLarge` ### Description The client attempted to transfer content larger than the server could accept at the present time. The client may retry at a later time. ### Bases `AMQPException` ``` -------------------------------- ### rabbitpy.exceptions.ActionException Source: https://gmr.github.io/rabbitpy/api/exceptions Raised when an action is attempted on a rabbitpy object that is not supported due to its current state. ```APIDOC ## rabbitpy.exceptions.ActionException Bases: `RabbitpyException` Raised when an action is taken on a Rabbitpy object that is not supported due to the state of the object. An example would be trying to ack a Message object when the message object was locally created and not sent by RabbitMQ via an AMQP Basic.Get or Basic.Consume. ``` -------------------------------- ### AMQPNoConsumers Source: https://gmr.github.io/rabbitpy/api/exceptions Raised when the exchange cannot deliver to a consumer with the immediate flag set, due to pending data or absence of consumers. ```APIDOC ## `rabbitpy.exceptions.AMQPNoConsumers` ### Description When the exchange cannot deliver to a consumer when the immediate flag is set. As a result of pending data on the queue or the absence of any consumers of the queue. ### Bases `AMQPException` ``` -------------------------------- ### AMQPNotAllowed Source: https://gmr.github.io/rabbitpy/api/exceptions Raised when the client attempts to work with an entity in a prohibited manner due to security settings or other criteria. ```APIDOC ## `rabbitpy.exceptions.AMQPNotAllowed` ### Description The client tried to work with some entity in a manner that is prohibited by the server, due to security settings or by some other criteria. ### Bases `AMQPException` ``` -------------------------------- ### rabbitpy.exceptions.UnexpectedResponseError Source: https://gmr.github.io/rabbitpy/api/exceptions Raised when an RPC call to RabbitMQ returns an unrecognized response. ```APIDOC ## rabbitpy.exceptions.UnexpectedResponseError Bases: `RabbitpyException` Raised when an RPC call is made to RabbitMQ but the response it sent back is not recognized. ``` -------------------------------- ### rabbitpy.exceptions.RabbitpyException Source: https://gmr.github.io/rabbitpy/api/exceptions The base exception class for all exceptions raised by the rabbitpy library. ```APIDOC ## rabbitpy.exceptions.RabbitpyException Bases: `Exception` Base exception for all rabbitpy exceptions. ``` -------------------------------- ### AMQPResourceLocked Source: https://gmr.github.io/rabbitpy/api/exceptions Raised when the client attempts to work with a server entity to which it has no access because another client is using it. ```APIDOC ## `rabbitpy.exceptions.AMQPResourceLocked` ### Description The client attempted to work with a server entity to which it has no access because another client is working with it. ### Bases `AMQPException` ``` -------------------------------- ### rabbitpy.exceptions.AMQPChannelError Source: https://gmr.github.io/rabbitpy/api/exceptions Raised when a client attempts to operate on a channel that has not been correctly opened, indicating a potential client-side error. ```APIDOC ## rabbitpy.exceptions.AMQPChannelError Bases: `AMQPException` The client attempted to work with a channel that had not been correctly opened. This most likely indicates a fault in the client layer. ``` -------------------------------- ### AMQPUnexpectedFrame Source: https://gmr.github.io/rabbitpy/api/exceptions Raised when the peer sends an unexpected frame, often in the context of content header and body, indicating a fault in content processing. ```APIDOC ## `rabbitpy.exceptions.AMQPUnexpectedFrame` ### Description The peer sent a frame that was not expected, usually in the context of a content header and body. This strongly indicates a fault in the peer's content processing. ### Bases `AMQPException` ``` -------------------------------- ### AMQPInternalError Source: https://gmr.github.io/rabbitpy/api/exceptions Raised when the server cannot complete a method due to an internal error, potentially requiring operator intervention. ```APIDOC ## `rabbitpy.exceptions.AMQPInternalError` ### Description The server could not complete the method because of an internal error. The server may require intervention by an operator in order to resume normal operations. ### Bases `AMQPException` ``` -------------------------------- ### AMQPFrameError Source: https://gmr.github.io/rabbitpy/api/exceptions Raised when the sender sends a malformed frame that the recipient could not decode, indicating a programming error in the sending peer. ```APIDOC ## `rabbitpy.exceptions.AMQPFrameError` ### Description The sender sent a malformed frame that the recipient could not decode. This strongly implies a programming error in the sending peer. ### Bases `AMQPException` ``` -------------------------------- ### rabbitpy.exceptions.TooManyChannelsError Source: https://gmr.github.io/rabbitpy/api/exceptions Raised if an attempt is made to create a channel that exceeds the maximum allowed channels for a single connection (2,147,483,647). ```APIDOC ## rabbitpy.exceptions.TooManyChannelsError Bases: `RabbitpyException` Raised if an application attempts to create a channel, exceeding the maximum number of channels (MAXINT or 2,147,483,647) available for a single connection. Note that each time a channel object is created, it will take a new channel id. If you create and destroy 2,147,483,648 channels, this exception will be raised. ``` -------------------------------- ### rabbitpy.exceptions.AMQPCommandInvalid Source: https://gmr.github.io/rabbitpy/api/exceptions Raised when the client sends an invalid sequence of frames, performing an operation deemed invalid by the server, typically due to a client programming error. ```APIDOC ## rabbitpy.exceptions.AMQPCommandInvalid Bases: `AMQPException` The client sent an invalid sequence of frames, attempting to perform an operation that was considered invalid by the server. This usually implies a programming error in the client. ``` -------------------------------- ### rabbitpy.exceptions.AMQPConnectionForced Source: https://gmr.github.io/rabbitpy/api/exceptions Raised when an operator intervenes to close the connection; the client may retry later. ```APIDOC ## rabbitpy.exceptions.AMQPConnectionForced Bases: `AMQPException` An operator intervened to close the connection for some reason. The client may retry at some later date. ``` -------------------------------- ### AMQPSyntaxError Source: https://gmr.github.io/rabbitpy/api/exceptions Raised when the sender sends a frame with illegal values, indicating a programming error in the sending peer. ```APIDOC ## `rabbitpy.exceptions.AMQPSyntaxError` ### Description The sender sent a frame that contained illegal values for one or more fields. This strongly implies a programming error in the sending peer. ### Bases `AMQPException` ``` -------------------------------- ### rabbitpy.exceptions.ConnectionClosed Source: https://gmr.github.io/rabbitpy/api/exceptions Raised if `connection.close()` is invoked when the connection is not currently open. ```APIDOC ## rabbitpy.exceptions.ConnectionClosed Bases: `ConnectionException` Raised if a connection.close() is invoked when the connection is not open. ``` -------------------------------- ### rabbitpy.exceptions.MessageReturnedException Source: https://gmr.github.io/rabbitpy/api/exceptions Raised when RabbitMQ returns a message to the publisher via the `Basic.Return` RPC call. ```APIDOC ## rabbitpy.exceptions.MessageReturnedException Bases: `RabbitpyException` Raised if the RabbitMQ sends a message back to a publisher via the Basic.Return RPC call. ``` -------------------------------- ### rabbitpy.exceptions.RemoteClosedChannelException Source: https://gmr.github.io/rabbitpy/api/exceptions Raised if RabbitMQ closes a channel and the `reply_code` in the `Channel.Close` RPC request does not map to a specific rabbitpy exception. ```APIDOC ## rabbitpy.exceptions.RemoteClosedChannelException Bases: `RabbitpyException` Raised if RabbitMQ closes the channel and the reply_code in the Channel.Close RPC request does not have a mapped exception in Rabbitpy. ``` -------------------------------- ### rabbitpy.exceptions.ChannelClosedException Source: https://gmr.github.io/rabbitpy/api/exceptions Raised when an operation is attempted on a channel that has been closed. ```APIDOC ## rabbitpy.exceptions.ChannelClosedException Bases: `RabbitpyException` Raised when an action is attempted on a channel that is closed. ``` -------------------------------- ### rabbitpy.exceptions.ConnectionResetException Source: https://gmr.github.io/rabbitpy/api/exceptions Raised if the socket-level connection is reset, potentially due to network issues, timeouts, or missed heartbeats. ```APIDOC ## rabbitpy.exceptions.ConnectionResetException Bases: `ConnectionException` Raised if the socket level connection was reset. This can happen due to the loss of network connection or socket timeout, or more than 2 missed heartbeat intervals if heartbeats are enabled. ``` -------------------------------- ### rabbitpy.exceptions.RemoteClosedException Source: https://gmr.github.io/rabbitpy/api/exceptions Raised if RabbitMQ closes the connection and the `reply_code` in the `Connection.Close` RPC request does not map to a specific rabbitpy exception. ```APIDOC ## rabbitpy.exceptions.RemoteClosedException Bases: `RabbitpyException` Raised if RabbitMQ closes the connection and the reply_code in the Connection.Close RPC request does not have a mapped exception in Rabbitpy. ``` -------------------------------- ### rabbitpy.exceptions.NoActiveTransactionError Source: https://gmr.github.io/rabbitpy/api/exceptions Raised when a transaction-related method is called but no transaction has been initiated. ```APIDOC ## rabbitpy.exceptions.NoActiveTransactionError Bases: `RabbitpyException` Raised when a transaction method is issued but the transaction has not been initiated. ``` -------------------------------- ### rabbitpy.exceptions.RemoteCancellationException Source: https://gmr.github.io/rabbitpy/api/exceptions Raised if RabbitMQ cancels an active consumer. ```APIDOC ## rabbitpy.exceptions.RemoteCancellationException Bases: `RabbitpyException` Raised if RabbitMQ cancels an active consumer ``` -------------------------------- ### rabbitpy.exceptions.ReceivedOnClosedChannelException Source: https://gmr.github.io/rabbitpy/api/exceptions Raised when RabbitMQ sends an RPC on a channel that has already been closed. ```APIDOC ## rabbitpy.exceptions.ReceivedOnClosedChannelException Bases: `RabbitpyException` Raised when RabbitMQ sends an RPC on a channel that is closed. ``` -------------------------------- ### rabbitpy.exceptions.NotConsumingError Source: https://gmr.github.io/rabbitpy/api/exceptions Raised if `Queue.cancel_consumer()` is called when the queue is not actively consuming messages. ```APIDOC ## rabbitpy.exceptions.NotConsumingError Bases: `RabbitpyException` Raised Queue.cancel_consumer() is invoked but the queue is not actively consuming. ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.