PyRabbit Documentation - Read the Docs · PyRabbit Documentation, Release 1.1.0 • auto_delete...
Transcript of PyRabbit Documentation - Read the Docs · PyRabbit Documentation, Release 1.1.0 • auto_delete...
PyRabbit DocumentationRelease 1.1.0
Brian K. Jones
October 26, 2016
Contents
1 The api Module 3
2 The http Module 11
3 Indices and tables 133.1 PyRabbit Overview . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 13
Python Module Index 15
i
ii
PyRabbit Documentation, Release 1.1.0
Contents:
Contents 1
PyRabbit Documentation, Release 1.1.0
2 Contents
CHAPTER 1
The api Module
The api module is the only module meant for use by users of the module, although that is not enforced. It exposesan interface for getting at all of the functionality provided by the RabbitMQ API. Where that is not true, it will beshortly ;-) The api module houses the Client class, which provides the main interface developers will use to interactwith RabbitMQ. It also contains errors and decorators used by the class.
exception pyrabbit.api.APIErrorDenotes a failure due to unexpected or invalid input/output between the client and the API
class pyrabbit.api.Client(api_url, user, passwd, timeout=5, scheme=’http’)Abstraction of the RabbitMQ Management HTTP API.
HTTP calls are delegated to the HTTPClient class for ease of testing, cleanliness, separation of duty, flexibility,etc.
create_binding(vhost, exchange, queue, rt_key=None, args=None)Creates a binding between an exchange and a queue on a given vhost.
Parameters
• vhost (string) – vhost housing the exchange/queue to bind
• exchange (string) – the target exchange of the binding
• queue (string) – the queue to bind to the exchange
• rt_key (string) – the routing key to use for the binding
• args (list) – extra arguments to associate w/ the binding.
Returns boolean
create_exchange(vhost, name, xtype, auto_delete=False, durable=True, internal=False, argu-ments=None)
Creates an exchange in the given vhost with the given name. As per the RabbitMQ API documentation, aJSON body also needs to be included that “looks something like this”:
{“type”:”direct”, “auto_delete”:false, “durable”:true, “internal”:false, “arguments”:[]}
On success, the API returns a 204 with no content, in which case this function returns True. If any otherresponse is received, it’s raised.
Parameters
• vhost (string) – Vhost to create the exchange in.
• name (string) – Name of the proposed exchange.
• type (string) – The AMQP exchange type.
3
PyRabbit Documentation, Release 1.1.0
• auto_delete (bool) – Whether or not the exchange should be dropped when the no.of consumers drops to zero.
• durable (bool) – Whether you want this exchange to persist a broker restart.
• internal (bool) – Whether or not this is a queue for use by the broker only.
• arguments (list) – If given, should be a list. If not given, an empty list is sent.
create_queue(vhost, name, **kwargs)Create a queue. The API documentation specifies that all of the body elements are optional, so this methodonly requires arguments needed to form the URI
Parameters
• vhost (string) – The vhost to create the queue in.
• name (string) – The name of the queue
More on these operations can be found at: http://www.rabbitmq.com/amqp-0-9-1-reference.html
create_user(username, password, tags=’‘)Creates a user.
Parameters
• username (string) – The name to give to the new user
• password (string) – Password for the new user
• tags (string) – Comma-separated list of tags for the user
Returns boolean
create_vhost(vname)Creates a vhost on the server to house exchanges.
Parameters vname (string) – The name to give to the vhost on the server
Returns boolean
delete_binding(vhost, exchange, queue, rt_key)Deletes a binding between an exchange and a queue on a given vhost.
Parameters
• vhost (string) – vhost housing the exchange/queue to bind
• exchange (string) – the target exchange of the binding
• queue (string) – the queue to bind to the exchange
• rt_key (string) – the routing key to use for the binding
delete_connection(name)Close the named connection. The API returns a 204 on success, in which case this method returns True,otherwise the error is raised.
Parameters name (string) – The name of the connection to delete.
Returns bool True on success.
delete_exchange(vhost, name)Delete the named exchange from the named vhost. The API returns a 204 on success, in which case thismethod returns True, otherwise the error is raised.
Parameters
4 Chapter 1. The api Module
PyRabbit Documentation, Release 1.1.0
• vhost (string) – Vhost where target exchange was created
• name (string) – The name of the exchange to delete.
Returns bool True on success.
delete_permission(vname, username)Delete permission for a given username on a given vhost. Both must already exist.
Parameters
• vname (string) – Name of the vhost to set perms on.
• username (string) – User to set permissions for.
delete_queue(vhost, qname)Deletes the named queue from the named vhost.
Parameters
• vhost (string) – Vhost housing the queue to be deleted.
• qname (string) – Name of the queue to delete.
Note that if you just want to delete the messages from a queue, you should use purge_queue instead ofdeleting/recreating a queue.
delete_user(username)Deletes a user from the server.
Parameters username (string) – Name of the user to delete from the server.
delete_vhost(vname)Deletes a vhost from the server. Note that this also deletes any exchanges or queues that belong to thisvhost.
Parameters vname (string) – Name of the vhost to delete from the server.
get_all_vhosts()Lists the names of all RabbitMQ vhosts.
Returns a list of dicts, each dict representing a vhost on the broker.
get_bindings()
Returns list of dicts
get_channel(name)Get a channel by name. To get the names, use get_channels.
Parameters name (string) – Name of channel to get
Returns dict conn A channel attribute dictionary.
get_channels()Return a list of dicts containing details about broker connections. :returns: list of dicts
get_connection(name)Get a connection by name. To get the names, use get_connections.
Parameters name (string) – Name of connection to get
Returns dict conn A connection attribute dictionary.
get_connections()
Returns list of dicts, or an empty list if there are no connections.
5
PyRabbit Documentation, Release 1.1.0
get_exchange(vhost, name)Gets a single exchange which requires a vhost and name.
Parameters
• vhost (string) – The vhost containing the target exchange
• name (string) – The name of the exchange
Returns dict
get_exchanges(vhost=None)
Returns A list of dicts
Parameters vhost (string) – A vhost to query for exchanges, or None (default), whichtriggers a query for all exchanges in all vhosts.
get_messages(vhost, qname, count=1, requeue=False, truncate=None, encoding=’auto’)Gets <count> messages from the queue.
Parameters
• vhost (string) – Name of vhost containing the queue
• qname (string) – Name of the queue to consume from
• count (int) – Number of messages to get.
• requeue (bool) – Whether to requeue the message after getting it. This will cause the‘redelivered’ flag to be set in the message on the queue.
• truncate (int) – The length, in bytes, beyond which the server will truncate the mes-sage before returning it.
Returns list of dicts. messages[msg-index][’payload’] will contain the message body.
get_nodes()
Return type dict
Returns a list of dictionaries, each containing the details of each node of the cluster.
get_overview()
Return type dict
Data in the ‘overview’ depends on the privileges of the creds used, but typically contains information aboutthe management plugin version, some high-level message stats, and aggregate queue totals. Admin-levelcreds gets you information about the cluster node, listeners, etc.
get_permission(vname, username)
Returns dicts of permissions.
Parameters
• vname (string) – Name of the vhost to set perms on.
• username (string) – User to set permissions for.
get_permissions()
Returns list of dicts, or an empty list if there are no permissions.
get_queue(vhost, name)Get a single queue, which requires both vhost and name.
Parameters
6 Chapter 1. The api Module
PyRabbit Documentation, Release 1.1.0
• vhost (string) – The virtual host for the queue being requested. If the vhost is ‘/’,note that it will be translated to ‘%2F’ to conform to URL encoding requirements.
• name (string) – The name of the queue being requested.
Returns A dictionary of queue properties.
Return type dict
get_queue_bindings(vhost, qname)Return a list of dicts, one dict per binding. The dict format coming from RabbitMQ for queue named‘testq’ is:
{“source”:”sourceExch”,”vhost”:”/”,”destination”:”testq”, “destination_type”:”queue”,”routing_key”:”.”,”arguments”:{},“properties_key”:”%2A.%2A”}
get_queue_depth(vhost, name)
Get the number of messages currently in a queue. This is a convenience function that just callsClient.get_queue() and pulls out/returns the ‘messages’ field from the dictionary it returns.
Parameters
• vhost (string) – The vhost of the queue being queried.
• name (string) – The name of the queue to query.
Returns Number of messages in the queue
Return type integer
get_queue_depths(vhost, names=None)Get the number of messages currently sitting in either the queue names listed in ‘names’, or all queues in‘vhost’ if no ‘names’ are given.
Parameters
• vhost (str) – Vhost where queues in ‘names’ live.
• names (list) – OPTIONAL - Specific queues to show depths for. If None, show depthsfor all queues in ‘vhost’.
get_queues(vhost=None)Get all queues, or all queues in a vhost if vhost is not None. Returns a list.
Parameters vhost (string) – The virtual host to list queues for. If This is None (the default),all queues for the broker instance are returned.
Returns A list of dicts, each representing a queue.
Return type list of dicts
get_user_permissions(username)
Returns list of dicts, or an empty list if there are no permissions.
Parameters username (string) – User to set permissions for.
get_users()Returns a list of dictionaries, each containing the attributes of a different RabbitMQ user.
Returns a list of dictionaries, each representing a user.
get_vhost(vname)Returns the attributes of a single named vhost in a dict.
7
PyRabbit Documentation, Release 1.1.0
Parameters vname (string) – Name of the vhost to get.
Returns dict vhost Attribute dict for the named vhost
get_vhost_names()A convenience function for getting back only the vhost names instead of the larger vhost dicts.
Returns list vhost_names A list of just the vhost names.
get_vhost_permissions(vname)
Returns list of dicts, or an empty list if there are no permissions.
Parameters vname (string) – Name of the vhost to set perms on.
get_whoami()A convenience function used in the event that you need to confirm that the broker thinks you are who youthink you are.
Returns dict whoami Dict structure contains: * administrator: whether the user is has adminprivileges * name: user name * auth_backend: backend used to determine admin rights
is_alive(vhost=’%2F’)Uses the aliveness-test API call to determine if the server is alive and the vhost is active. The broker (notthis code) creates a queue and then sends/consumes a message from it.
Parameters vhost (string) – There should be no real reason to ever change this from thedefault value, but it’s there if you need to.
Returns bool True if alive, False otherwise
Raises HTTPError if vhost doesn’t exist on the broker.
publish(vhost, xname, rt_key, payload, payload_enc=’string’, properties=None)Publish a message to an exchange.
Parameters
• vhost (string) – vhost housing the target exchange
• xname (string) – name of the target exchange
• rt_key (string) – routing key for message
• payload (string) – the message body for publishing
• payload_enc (string) – encoding of the payload. The only choices here are ‘string’and ‘base64’.
• properties (dict) – a dict of message properties
Returns boolean indicating success or failure.
purge_queue(vhost, name)Purge all messages from a single queue. This is a convenience method so you aren’t forced to supply a listcontaining a single tuple to the purge_queues method.
Parameters
• vhost (string) – The vhost of the queue being purged.
• name (string) – The name of the queue being purged.
Return type None
purge_queues(queues)Purge all messages from one or more queues.
8 Chapter 1. The api Module
PyRabbit Documentation, Release 1.1.0
Parameters queues (list) – A list of (‘qname’, ‘vhost’) tuples.
Returns True on success
set_vhost_permissions(vname, username, config, rd, wr)Set permissions for a given username on a given vhost. Both must already exist.
Parameters
• vname (string) – Name of the vhost to set perms on.
• username (string) – User to set permissions for.
• config (string) – Permission pattern for configuration operations for this user in thisvhost.
• rd (string) – Permission pattern for read operations for this user in this vhost
• wr (string) – Permission pattern for write operations for this user in this vhost.
Permission patterns are regex strings. If you’re unfamiliar with this, you should definitely check out thissection of the RabbitMQ docs:
http://www.rabbitmq.com/admin-guide.html#access-control
exception pyrabbit.api.PermissionErrorRaised if the operation requires admin permissions, and the user used to instantiate the Client class does nothave admin privileges.
9
PyRabbit Documentation, Release 1.1.0
10 Chapter 1. The api Module
CHAPTER 2
The http Module
The http module wraps the underlying raw HTTP request module (requests currently) to separate the job of exposingthe API from the job of dealing with lower-level interfacing with the HTTP client in use today.
class pyrabbit.http.HTTPClient(api_url, uname, passwd, timeout=5, scheme=’http’)A wrapper for requests. Abstracts away things like path building, return value parsing, etc., so the api modulecode stays clean and easy to read/use.
do_call(path, method, body=None, headers=None)Send an HTTP request to the REST API.
Parameters
• path (string) – A URL
• method (string) – The HTTP method (GET, POST, etc.) to use in the request.
• body (string) – A string representing any data to be sent in the body of the HTTPrequest.
• headers (dictionary) – “{header-name: header-value}” dictionary.
exception pyrabbit.http.HTTPError(content, status=None, reason=None, path=None, body=None)An error response from the API server. This should be an HTTP error of some kind (404, 500, etc).
exception pyrabbit.http.NetworkErrorDenotes a failure to communicate with the REST API
11
PyRabbit Documentation, Release 1.1.0
12 Chapter 2. The http Module
CHAPTER 3
Indices and tables
• genindex
• modindex
• search
3.1 PyRabbit Overview
pyrabbit is a module to make it easy to interface w/ RabbitMQ’s HTTP Management API. It’s tested against RabbitMQ2.4.1 using Python 2.6-3.2. Yes, it works great w/ Python 3!
Here’s a quick demo:
>>> from pyrabbit.api import Client>>> cl = Client('http://localhost:55672/api', 'guest', 'guest')>>> cl.is_alive()True>>> cl.create_vhost('example_vhost')True>>> [i['name'] for i in cl.get_all_vhosts()][u'/', u'diabolica', u'example_vhost', u'testvhost']>>> cl.get_vhost_names()[u'/', u'diabolica', u'example_vhost', u'testvhost']>>> cl.set_vhost_permissions('example_vhost', 'guest', '.*', '.*', '.*')True>>> cl.create_exchange('example_vhost', 'example_exchange', 'direct')True>>> cl.get_exchange('example_vhost', 'example_exchange'){u'name': u'example_exchange', u'durable': True, u'vhost': u'example_vhost', u'internal': False, u'arguments': {}, u'type': u'direct', u'auto_delete': False}>>> cl.create_queue('example_queue', 'example_vhost')True>>> cl.create_binding('example_vhost', 'example_exchange', 'example_queue', 'my.rtkey')True>>> cl.publish('example_vhost', 'example_exchange', 'my.rtkey', 'example message payload')True>>> cl.get_messages('example_vhost', 'example_queue')[{u'payload': u'example message payload', u'exchange': u'example_exchange', u'routing_key': u'my.rtkey', u'payload_bytes': 23, u'message_count': 2, u'payload_encoding': u'string', u'redelivered': False, u'properties': []}]>>> cl.delete_vhost('example_vhost')True>>> [i['name'] for i in cl.get_all_vhosts()][u'/', u'diabolica', u'testvhost']
13
PyRabbit Documentation, Release 1.1.0
14 Chapter 3. Indices and tables
Python Module Index
ppyrabbit.api, 3pyrabbit.http, 11
15
PyRabbit Documentation, Release 1.1.0
16 Python Module Index
Index
AAPIError, 3
CClient (class in pyrabbit.api), 3create_binding() (pyrabbit.api.Client method), 3create_exchange() (pyrabbit.api.Client method), 3create_queue() (pyrabbit.api.Client method), 4create_user() (pyrabbit.api.Client method), 4create_vhost() (pyrabbit.api.Client method), 4
Ddelete_binding() (pyrabbit.api.Client method), 4delete_connection() (pyrabbit.api.Client method), 4delete_exchange() (pyrabbit.api.Client method), 4delete_permission() (pyrabbit.api.Client method), 5delete_queue() (pyrabbit.api.Client method), 5delete_user() (pyrabbit.api.Client method), 5delete_vhost() (pyrabbit.api.Client method), 5do_call() (pyrabbit.http.HTTPClient method), 11
Gget_all_vhosts() (pyrabbit.api.Client method), 5get_bindings() (pyrabbit.api.Client method), 5get_channel() (pyrabbit.api.Client method), 5get_channels() (pyrabbit.api.Client method), 5get_connection() (pyrabbit.api.Client method), 5get_connections() (pyrabbit.api.Client method), 5get_exchange() (pyrabbit.api.Client method), 5get_exchanges() (pyrabbit.api.Client method), 6get_messages() (pyrabbit.api.Client method), 6get_nodes() (pyrabbit.api.Client method), 6get_overview() (pyrabbit.api.Client method), 6get_permission() (pyrabbit.api.Client method), 6get_permissions() (pyrabbit.api.Client method), 6get_queue() (pyrabbit.api.Client method), 6get_queue_bindings() (pyrabbit.api.Client method), 7get_queue_depth() (pyrabbit.api.Client method), 7get_queue_depths() (pyrabbit.api.Client method), 7get_queues() (pyrabbit.api.Client method), 7
get_user_permissions() (pyrabbit.api.Client method), 7get_users() (pyrabbit.api.Client method), 7get_vhost() (pyrabbit.api.Client method), 7get_vhost_names() (pyrabbit.api.Client method), 8get_vhost_permissions() (pyrabbit.api.Client method), 8get_whoami() (pyrabbit.api.Client method), 8
HHTTPClient (class in pyrabbit.http), 11HTTPError, 11
Iis_alive() (pyrabbit.api.Client method), 8
NNetworkError, 11
PPermissionError, 9publish() (pyrabbit.api.Client method), 8purge_queue() (pyrabbit.api.Client method), 8purge_queues() (pyrabbit.api.Client method), 8pyrabbit.api (module), 3pyrabbit.http (module), 11
Sset_vhost_permissions() (pyrabbit.api.Client method), 9
17