repository_name
stringlengths
5
67
func_path_in_repository
stringlengths
4
234
func_name
stringlengths
0
314
whole_func_string
stringlengths
52
3.87M
language
stringclasses
6 values
func_code_string
stringlengths
52
3.87M
func_documentation_string
stringlengths
1
47.2k
func_code_url
stringlengths
85
339
eandersson/amqpstorm
amqpstorm/io.py
IO._get_socket_addresses
def _get_socket_addresses(self): """Get Socket address information. :rtype: list """ family = socket.AF_UNSPEC if not socket.has_ipv6: family = socket.AF_INET try: addresses = socket.getaddrinfo(self._parameters['hostname'], self._parameters['port'], family, socket.SOCK_STREAM) except socket.gaierror as why: raise AMQPConnectionError(why) return addresses
python
def _get_socket_addresses(self): """Get Socket address information. :rtype: list """ family = socket.AF_UNSPEC if not socket.has_ipv6: family = socket.AF_INET try: addresses = socket.getaddrinfo(self._parameters['hostname'], self._parameters['port'], family, socket.SOCK_STREAM) except socket.gaierror as why: raise AMQPConnectionError(why) return addresses
Get Socket address information. :rtype: list
https://github.com/eandersson/amqpstorm/blob/38330906c0af19eea482f43c5ce79bab98a1e064/amqpstorm/io.py#L152-L166
eandersson/amqpstorm
amqpstorm/io.py
IO._find_address_and_connect
def _find_address_and_connect(self, addresses): """Find and connect to the appropriate address. :param addresses: :raises AMQPConnectionError: Raises if the connection encountered an error. :rtype: socket.socket """ error_message = None for address in addresses: sock = self._create_socket(socket_family=address[0]) try: sock.connect(address[4]) except (IOError, OSError) as why: error_message = why.strerror continue return sock raise AMQPConnectionError( 'Could not connect to %s:%d error: %s' % ( self._parameters['hostname'], self._parameters['port'], error_message ) )
python
def _find_address_and_connect(self, addresses): """Find and connect to the appropriate address. :param addresses: :raises AMQPConnectionError: Raises if the connection encountered an error. :rtype: socket.socket """ error_message = None for address in addresses: sock = self._create_socket(socket_family=address[0]) try: sock.connect(address[4]) except (IOError, OSError) as why: error_message = why.strerror continue return sock raise AMQPConnectionError( 'Could not connect to %s:%d error: %s' % ( self._parameters['hostname'], self._parameters['port'], error_message ) )
Find and connect to the appropriate address. :param addresses: :raises AMQPConnectionError: Raises if the connection encountered an error. :rtype: socket.socket
https://github.com/eandersson/amqpstorm/blob/38330906c0af19eea482f43c5ce79bab98a1e064/amqpstorm/io.py#L168-L192
eandersson/amqpstorm
amqpstorm/io.py
IO._create_socket
def _create_socket(self, socket_family): """Create Socket. :param int socket_family: :rtype: socket.socket """ sock = socket.socket(socket_family, socket.SOCK_STREAM, 0) sock.settimeout(self._parameters['timeout'] or None) if self.use_ssl: if not compatibility.SSL_SUPPORTED: raise AMQPConnectionError( 'Python not compiled with support for TLSv1 or higher' ) sock = self._ssl_wrap_socket(sock) return sock
python
def _create_socket(self, socket_family): """Create Socket. :param int socket_family: :rtype: socket.socket """ sock = socket.socket(socket_family, socket.SOCK_STREAM, 0) sock.settimeout(self._parameters['timeout'] or None) if self.use_ssl: if not compatibility.SSL_SUPPORTED: raise AMQPConnectionError( 'Python not compiled with support for TLSv1 or higher' ) sock = self._ssl_wrap_socket(sock) return sock
Create Socket. :param int socket_family: :rtype: socket.socket
https://github.com/eandersson/amqpstorm/blob/38330906c0af19eea482f43c5ce79bab98a1e064/amqpstorm/io.py#L194-L208
eandersson/amqpstorm
amqpstorm/io.py
IO._ssl_wrap_socket
def _ssl_wrap_socket(self, sock): """Wrap SSLSocket around the Socket. :param socket.socket sock: :rtype: SSLSocket """ context = self._parameters['ssl_options'].get('context') if context is not None: hostname = self._parameters['ssl_options'].get('server_hostname') return context.wrap_socket( sock, do_handshake_on_connect=True, server_hostname=hostname ) if 'ssl_version' not in self._parameters['ssl_options']: self._parameters['ssl_options']['ssl_version'] = ( compatibility.DEFAULT_SSL_VERSION ) return ssl.wrap_socket( sock, do_handshake_on_connect=True, **self._parameters['ssl_options'] )
python
def _ssl_wrap_socket(self, sock): """Wrap SSLSocket around the Socket. :param socket.socket sock: :rtype: SSLSocket """ context = self._parameters['ssl_options'].get('context') if context is not None: hostname = self._parameters['ssl_options'].get('server_hostname') return context.wrap_socket( sock, do_handshake_on_connect=True, server_hostname=hostname ) if 'ssl_version' not in self._parameters['ssl_options']: self._parameters['ssl_options']['ssl_version'] = ( compatibility.DEFAULT_SSL_VERSION ) return ssl.wrap_socket( sock, do_handshake_on_connect=True, **self._parameters['ssl_options'] )
Wrap SSLSocket around the Socket. :param socket.socket sock: :rtype: SSLSocket
https://github.com/eandersson/amqpstorm/blob/38330906c0af19eea482f43c5ce79bab98a1e064/amqpstorm/io.py#L210-L230
eandersson/amqpstorm
amqpstorm/io.py
IO._create_inbound_thread
def _create_inbound_thread(self): """Internal Thread that handles all incoming traffic. :rtype: threading.Thread """ inbound_thread = threading.Thread(target=self._process_incoming_data, name=__name__) inbound_thread.daemon = True inbound_thread.start() return inbound_thread
python
def _create_inbound_thread(self): """Internal Thread that handles all incoming traffic. :rtype: threading.Thread """ inbound_thread = threading.Thread(target=self._process_incoming_data, name=__name__) inbound_thread.daemon = True inbound_thread.start() return inbound_thread
Internal Thread that handles all incoming traffic. :rtype: threading.Thread
https://github.com/eandersson/amqpstorm/blob/38330906c0af19eea482f43c5ce79bab98a1e064/amqpstorm/io.py#L232-L241
eandersson/amqpstorm
amqpstorm/io.py
IO._process_incoming_data
def _process_incoming_data(self): """Retrieve and process any incoming data. :return: """ while self._running.is_set(): if self.poller.is_ready: self.data_in += self._receive() self.data_in = self._on_read_impl(self.data_in)
python
def _process_incoming_data(self): """Retrieve and process any incoming data. :return: """ while self._running.is_set(): if self.poller.is_ready: self.data_in += self._receive() self.data_in = self._on_read_impl(self.data_in)
Retrieve and process any incoming data. :return:
https://github.com/eandersson/amqpstorm/blob/38330906c0af19eea482f43c5ce79bab98a1e064/amqpstorm/io.py#L243-L251
eandersson/amqpstorm
amqpstorm/io.py
IO._receive
def _receive(self): """Receive any incoming socket data. If an error is thrown, handle it and return an empty string. :return: data_in :rtype: bytes """ data_in = EMPTY_BUFFER try: data_in = self._read_from_socket() except socket.timeout: pass except (IOError, OSError) as why: if why.args[0] not in (EWOULDBLOCK, EAGAIN): self._exceptions.append(AMQPConnectionError(why)) self._running.clear() return data_in
python
def _receive(self): """Receive any incoming socket data. If an error is thrown, handle it and return an empty string. :return: data_in :rtype: bytes """ data_in = EMPTY_BUFFER try: data_in = self._read_from_socket() except socket.timeout: pass except (IOError, OSError) as why: if why.args[0] not in (EWOULDBLOCK, EAGAIN): self._exceptions.append(AMQPConnectionError(why)) self._running.clear() return data_in
Receive any incoming socket data. If an error is thrown, handle it and return an empty string. :return: data_in :rtype: bytes
https://github.com/eandersson/amqpstorm/blob/38330906c0af19eea482f43c5ce79bab98a1e064/amqpstorm/io.py#L253-L270
eandersson/amqpstorm
amqpstorm/io.py
IO._read_from_socket
def _read_from_socket(self): """Read data from the socket. :rtype: bytes """ if not self.use_ssl: if not self.socket: raise socket.error('connection/socket error') return self.socket.recv(MAX_FRAME_SIZE) with self._rd_lock: if not self.socket: raise socket.error('connection/socket error') return self.socket.read(MAX_FRAME_SIZE)
python
def _read_from_socket(self): """Read data from the socket. :rtype: bytes """ if not self.use_ssl: if not self.socket: raise socket.error('connection/socket error') return self.socket.recv(MAX_FRAME_SIZE) with self._rd_lock: if not self.socket: raise socket.error('connection/socket error') return self.socket.read(MAX_FRAME_SIZE)
Read data from the socket. :rtype: bytes
https://github.com/eandersson/amqpstorm/blob/38330906c0af19eea482f43c5ce79bab98a1e064/amqpstorm/io.py#L272-L285
eandersson/amqpstorm
amqpstorm/heartbeat.py
Heartbeat.start
def start(self, exceptions): """Start the Heartbeat Checker. :param list exceptions: :return: """ if not self._interval: return False self._running.set() with self._lock: self._threshold = 0 self._reads_since_check = 0 self._writes_since_check = 0 self._exceptions = exceptions LOGGER.debug('Heartbeat Checker Started') return self._start_new_timer()
python
def start(self, exceptions): """Start the Heartbeat Checker. :param list exceptions: :return: """ if not self._interval: return False self._running.set() with self._lock: self._threshold = 0 self._reads_since_check = 0 self._writes_since_check = 0 self._exceptions = exceptions LOGGER.debug('Heartbeat Checker Started') return self._start_new_timer()
Start the Heartbeat Checker. :param list exceptions: :return:
https://github.com/eandersson/amqpstorm/blob/38330906c0af19eea482f43c5ce79bab98a1e064/amqpstorm/heartbeat.py#L40-L55
eandersson/amqpstorm
amqpstorm/heartbeat.py
Heartbeat.stop
def stop(self): """Stop the Heartbeat Checker. :return: """ self._running.clear() with self._lock: if self._timer: self._timer.cancel() self._timer = None
python
def stop(self): """Stop the Heartbeat Checker. :return: """ self._running.clear() with self._lock: if self._timer: self._timer.cancel() self._timer = None
Stop the Heartbeat Checker. :return:
https://github.com/eandersson/amqpstorm/blob/38330906c0af19eea482f43c5ce79bab98a1e064/amqpstorm/heartbeat.py#L57-L66
eandersson/amqpstorm
amqpstorm/heartbeat.py
Heartbeat._check_for_life_signs
def _check_for_life_signs(self): """Check Connection for life signs. First check if any data has been sent, if not send a heartbeat to the remote server. If we have not received any data what so ever within two intervals, we need to raise an exception so that we can close the connection. :rtype: bool """ if not self._running.is_set(): return False if self._writes_since_check == 0: self.send_heartbeat_impl() self._lock.acquire() try: if self._reads_since_check == 0: self._threshold += 1 if self._threshold >= 2: self._running.clear() self._raise_or_append_exception() return False else: self._threshold = 0 finally: self._reads_since_check = 0 self._writes_since_check = 0 self._lock.release() return self._start_new_timer()
python
def _check_for_life_signs(self): """Check Connection for life signs. First check if any data has been sent, if not send a heartbeat to the remote server. If we have not received any data what so ever within two intervals, we need to raise an exception so that we can close the connection. :rtype: bool """ if not self._running.is_set(): return False if self._writes_since_check == 0: self.send_heartbeat_impl() self._lock.acquire() try: if self._reads_since_check == 0: self._threshold += 1 if self._threshold >= 2: self._running.clear() self._raise_or_append_exception() return False else: self._threshold = 0 finally: self._reads_since_check = 0 self._writes_since_check = 0 self._lock.release() return self._start_new_timer()
Check Connection for life signs. First check if any data has been sent, if not send a heartbeat to the remote server. If we have not received any data what so ever within two intervals, we need to raise an exception so that we can close the connection. :rtype: bool
https://github.com/eandersson/amqpstorm/blob/38330906c0af19eea482f43c5ce79bab98a1e064/amqpstorm/heartbeat.py#L68-L99
eandersson/amqpstorm
amqpstorm/heartbeat.py
Heartbeat._raise_or_append_exception
def _raise_or_append_exception(self): """The connection is presumably dead and we need to raise or append an exception. If we have a list for exceptions, append the exception and let the connection handle it, if not raise the exception here. :return: """ message = ( 'Connection dead, no heartbeat or data received in >= ' '%ds' % ( self._interval * 2 ) ) why = AMQPConnectionError(message) if self._exceptions is None: raise why self._exceptions.append(why)
python
def _raise_or_append_exception(self): """The connection is presumably dead and we need to raise or append an exception. If we have a list for exceptions, append the exception and let the connection handle it, if not raise the exception here. :return: """ message = ( 'Connection dead, no heartbeat or data received in >= ' '%ds' % ( self._interval * 2 ) ) why = AMQPConnectionError(message) if self._exceptions is None: raise why self._exceptions.append(why)
The connection is presumably dead and we need to raise or append an exception. If we have a list for exceptions, append the exception and let the connection handle it, if not raise the exception here. :return:
https://github.com/eandersson/amqpstorm/blob/38330906c0af19eea482f43c5ce79bab98a1e064/amqpstorm/heartbeat.py#L101-L119
eandersson/amqpstorm
amqpstorm/heartbeat.py
Heartbeat._start_new_timer
def _start_new_timer(self): """Create a timer that will be used to periodically check the connection for heartbeats. :return: """ if not self._running.is_set(): return False self._timer = self.timer_impl( interval=self._interval, function=self._check_for_life_signs ) self._timer.daemon = True self._timer.start() return True
python
def _start_new_timer(self): """Create a timer that will be used to periodically check the connection for heartbeats. :return: """ if not self._running.is_set(): return False self._timer = self.timer_impl( interval=self._interval, function=self._check_for_life_signs ) self._timer.daemon = True self._timer.start() return True
Create a timer that will be used to periodically check the connection for heartbeats. :return:
https://github.com/eandersson/amqpstorm/blob/38330906c0af19eea482f43c5ce79bab98a1e064/amqpstorm/heartbeat.py#L121-L135
eandersson/amqpstorm
amqpstorm/exchange.py
Exchange.declare
def declare(self, exchange='', exchange_type='direct', passive=False, durable=False, auto_delete=False, arguments=None): """Declare an Exchange. :param str exchange: Exchange name :param str exchange_type: Exchange type :param bool passive: Do not create :param bool durable: Durable exchange :param bool auto_delete: Automatically delete when not in use :param dict arguments: Exchange key/value arguments :raises AMQPInvalidArgument: Invalid Parameters :raises AMQPChannelError: Raises if the channel encountered an error. :raises AMQPConnectionError: Raises if the connection encountered an error. :rtype: dict """ if not compatibility.is_string(exchange): raise AMQPInvalidArgument('exchange should be a string') elif not compatibility.is_string(exchange_type): raise AMQPInvalidArgument('exchange_type should be a string') elif not isinstance(passive, bool): raise AMQPInvalidArgument('passive should be a boolean') elif not isinstance(durable, bool): raise AMQPInvalidArgument('durable should be a boolean') elif not isinstance(auto_delete, bool): raise AMQPInvalidArgument('auto_delete should be a boolean') elif arguments is not None and not isinstance(arguments, dict): raise AMQPInvalidArgument('arguments should be a dict or None') declare_frame = pamqp_exchange.Declare(exchange=exchange, exchange_type=exchange_type, passive=passive, durable=durable, auto_delete=auto_delete, arguments=arguments) return self._channel.rpc_request(declare_frame)
python
def declare(self, exchange='', exchange_type='direct', passive=False, durable=False, auto_delete=False, arguments=None): """Declare an Exchange. :param str exchange: Exchange name :param str exchange_type: Exchange type :param bool passive: Do not create :param bool durable: Durable exchange :param bool auto_delete: Automatically delete when not in use :param dict arguments: Exchange key/value arguments :raises AMQPInvalidArgument: Invalid Parameters :raises AMQPChannelError: Raises if the channel encountered an error. :raises AMQPConnectionError: Raises if the connection encountered an error. :rtype: dict """ if not compatibility.is_string(exchange): raise AMQPInvalidArgument('exchange should be a string') elif not compatibility.is_string(exchange_type): raise AMQPInvalidArgument('exchange_type should be a string') elif not isinstance(passive, bool): raise AMQPInvalidArgument('passive should be a boolean') elif not isinstance(durable, bool): raise AMQPInvalidArgument('durable should be a boolean') elif not isinstance(auto_delete, bool): raise AMQPInvalidArgument('auto_delete should be a boolean') elif arguments is not None and not isinstance(arguments, dict): raise AMQPInvalidArgument('arguments should be a dict or None') declare_frame = pamqp_exchange.Declare(exchange=exchange, exchange_type=exchange_type, passive=passive, durable=durable, auto_delete=auto_delete, arguments=arguments) return self._channel.rpc_request(declare_frame)
Declare an Exchange. :param str exchange: Exchange name :param str exchange_type: Exchange type :param bool passive: Do not create :param bool durable: Durable exchange :param bool auto_delete: Automatically delete when not in use :param dict arguments: Exchange key/value arguments :raises AMQPInvalidArgument: Invalid Parameters :raises AMQPChannelError: Raises if the channel encountered an error. :raises AMQPConnectionError: Raises if the connection encountered an error. :rtype: dict
https://github.com/eandersson/amqpstorm/blob/38330906c0af19eea482f43c5ce79bab98a1e064/amqpstorm/exchange.py#L18-L55
eandersson/amqpstorm
amqpstorm/exchange.py
Exchange.delete
def delete(self, exchange='', if_unused=False): """Delete an Exchange. :param str exchange: Exchange name :param bool if_unused: Delete only if unused :raises AMQPInvalidArgument: Invalid Parameters :raises AMQPChannelError: Raises if the channel encountered an error. :raises AMQPConnectionError: Raises if the connection encountered an error. :rtype: dict """ if not compatibility.is_string(exchange): raise AMQPInvalidArgument('exchange should be a string') delete_frame = pamqp_exchange.Delete(exchange=exchange, if_unused=if_unused) return self._channel.rpc_request(delete_frame)
python
def delete(self, exchange='', if_unused=False): """Delete an Exchange. :param str exchange: Exchange name :param bool if_unused: Delete only if unused :raises AMQPInvalidArgument: Invalid Parameters :raises AMQPChannelError: Raises if the channel encountered an error. :raises AMQPConnectionError: Raises if the connection encountered an error. :rtype: dict """ if not compatibility.is_string(exchange): raise AMQPInvalidArgument('exchange should be a string') delete_frame = pamqp_exchange.Delete(exchange=exchange, if_unused=if_unused) return self._channel.rpc_request(delete_frame)
Delete an Exchange. :param str exchange: Exchange name :param bool if_unused: Delete only if unused :raises AMQPInvalidArgument: Invalid Parameters :raises AMQPChannelError: Raises if the channel encountered an error. :raises AMQPConnectionError: Raises if the connection encountered an error. :rtype: dict
https://github.com/eandersson/amqpstorm/blob/38330906c0af19eea482f43c5ce79bab98a1e064/amqpstorm/exchange.py#L57-L75
eandersson/amqpstorm
amqpstorm/exchange.py
Exchange.bind
def bind(self, destination='', source='', routing_key='', arguments=None): """Bind an Exchange. :param str destination: Exchange name :param str source: Exchange to bind to :param str routing_key: The routing key to use :param dict arguments: Bind key/value arguments :raises AMQPInvalidArgument: Invalid Parameters :raises AMQPChannelError: Raises if the channel encountered an error. :raises AMQPConnectionError: Raises if the connection encountered an error. :rtype: dict """ if not compatibility.is_string(destination): raise AMQPInvalidArgument('destination should be a string') elif not compatibility.is_string(source): raise AMQPInvalidArgument('source should be a string') elif not compatibility.is_string(routing_key): raise AMQPInvalidArgument('routing_key should be a string') elif arguments is not None and not isinstance(arguments, dict): raise AMQPInvalidArgument('arguments should be a dict or None') bind_frame = pamqp_exchange.Bind(destination=destination, source=source, routing_key=routing_key, arguments=arguments) return self._channel.rpc_request(bind_frame)
python
def bind(self, destination='', source='', routing_key='', arguments=None): """Bind an Exchange. :param str destination: Exchange name :param str source: Exchange to bind to :param str routing_key: The routing key to use :param dict arguments: Bind key/value arguments :raises AMQPInvalidArgument: Invalid Parameters :raises AMQPChannelError: Raises if the channel encountered an error. :raises AMQPConnectionError: Raises if the connection encountered an error. :rtype: dict """ if not compatibility.is_string(destination): raise AMQPInvalidArgument('destination should be a string') elif not compatibility.is_string(source): raise AMQPInvalidArgument('source should be a string') elif not compatibility.is_string(routing_key): raise AMQPInvalidArgument('routing_key should be a string') elif arguments is not None and not isinstance(arguments, dict): raise AMQPInvalidArgument('arguments should be a dict or None') bind_frame = pamqp_exchange.Bind(destination=destination, source=source, routing_key=routing_key, arguments=arguments) return self._channel.rpc_request(bind_frame)
Bind an Exchange. :param str destination: Exchange name :param str source: Exchange to bind to :param str routing_key: The routing key to use :param dict arguments: Bind key/value arguments :raises AMQPInvalidArgument: Invalid Parameters :raises AMQPChannelError: Raises if the channel encountered an error. :raises AMQPConnectionError: Raises if the connection encountered an error. :rtype: dict
https://github.com/eandersson/amqpstorm/blob/38330906c0af19eea482f43c5ce79bab98a1e064/amqpstorm/exchange.py#L77-L106
eandersson/amqpstorm
amqpstorm/exchange.py
Exchange.unbind
def unbind(self, destination='', source='', routing_key='', arguments=None): """Unbind an Exchange. :param str destination: Exchange name :param str source: Exchange to unbind from :param str routing_key: The routing key used :param dict arguments: Unbind key/value arguments :raises AMQPInvalidArgument: Invalid Parameters :raises AMQPChannelError: Raises if the channel encountered an error. :raises AMQPConnectionError: Raises if the connection encountered an error. :rtype: dict """ if not compatibility.is_string(destination): raise AMQPInvalidArgument('destination should be a string') elif not compatibility.is_string(source): raise AMQPInvalidArgument('source should be a string') elif not compatibility.is_string(routing_key): raise AMQPInvalidArgument('routing_key should be a string') elif arguments is not None and not isinstance(arguments, dict): raise AMQPInvalidArgument('arguments should be a dict or None') unbind_frame = pamqp_exchange.Unbind(destination=destination, source=source, routing_key=routing_key, arguments=arguments) return self._channel.rpc_request(unbind_frame)
python
def unbind(self, destination='', source='', routing_key='', arguments=None): """Unbind an Exchange. :param str destination: Exchange name :param str source: Exchange to unbind from :param str routing_key: The routing key used :param dict arguments: Unbind key/value arguments :raises AMQPInvalidArgument: Invalid Parameters :raises AMQPChannelError: Raises if the channel encountered an error. :raises AMQPConnectionError: Raises if the connection encountered an error. :rtype: dict """ if not compatibility.is_string(destination): raise AMQPInvalidArgument('destination should be a string') elif not compatibility.is_string(source): raise AMQPInvalidArgument('source should be a string') elif not compatibility.is_string(routing_key): raise AMQPInvalidArgument('routing_key should be a string') elif arguments is not None and not isinstance(arguments, dict): raise AMQPInvalidArgument('arguments should be a dict or None') unbind_frame = pamqp_exchange.Unbind(destination=destination, source=source, routing_key=routing_key, arguments=arguments) return self._channel.rpc_request(unbind_frame)
Unbind an Exchange. :param str destination: Exchange name :param str source: Exchange to unbind from :param str routing_key: The routing key used :param dict arguments: Unbind key/value arguments :raises AMQPInvalidArgument: Invalid Parameters :raises AMQPChannelError: Raises if the channel encountered an error. :raises AMQPConnectionError: Raises if the connection encountered an error. :rtype: dict
https://github.com/eandersson/amqpstorm/blob/38330906c0af19eea482f43c5ce79bab98a1e064/amqpstorm/exchange.py#L108-L137
eandersson/amqpstorm
amqpstorm/management/queue.py
Queue.get
def get(self, queue, virtual_host='/'): """Get Queue details. :param queue: Queue name :param str virtual_host: Virtual host name :raises ApiError: Raises if the remote server encountered an error. :raises ApiConnectionError: Raises if there was a connectivity issue. :rtype: dict """ virtual_host = quote(virtual_host, '') return self.http_client.get( API_QUEUE % ( virtual_host, queue ) )
python
def get(self, queue, virtual_host='/'): """Get Queue details. :param queue: Queue name :param str virtual_host: Virtual host name :raises ApiError: Raises if the remote server encountered an error. :raises ApiConnectionError: Raises if there was a connectivity issue. :rtype: dict """ virtual_host = quote(virtual_host, '') return self.http_client.get( API_QUEUE % ( virtual_host, queue ) )
Get Queue details. :param queue: Queue name :param str virtual_host: Virtual host name :raises ApiError: Raises if the remote server encountered an error. :raises ApiConnectionError: Raises if there was a connectivity issue. :rtype: dict
https://github.com/eandersson/amqpstorm/blob/38330906c0af19eea482f43c5ce79bab98a1e064/amqpstorm/management/queue.py#L15-L32
eandersson/amqpstorm
amqpstorm/management/queue.py
Queue.list
def list(self, virtual_host='/', show_all=False): """List Queues. :param str virtual_host: Virtual host name :param bool show_all: List all Queues :raises ApiError: Raises if the remote server encountered an error. :raises ApiConnectionError: Raises if there was a connectivity issue. :rtype: list """ if show_all: return self.http_client.get(API_QUEUES) virtual_host = quote(virtual_host, '') return self.http_client.get( API_QUEUES_VIRTUAL_HOST % virtual_host )
python
def list(self, virtual_host='/', show_all=False): """List Queues. :param str virtual_host: Virtual host name :param bool show_all: List all Queues :raises ApiError: Raises if the remote server encountered an error. :raises ApiConnectionError: Raises if there was a connectivity issue. :rtype: list """ if show_all: return self.http_client.get(API_QUEUES) virtual_host = quote(virtual_host, '') return self.http_client.get( API_QUEUES_VIRTUAL_HOST % virtual_host )
List Queues. :param str virtual_host: Virtual host name :param bool show_all: List all Queues :raises ApiError: Raises if the remote server encountered an error. :raises ApiConnectionError: Raises if there was a connectivity issue. :rtype: list
https://github.com/eandersson/amqpstorm/blob/38330906c0af19eea482f43c5ce79bab98a1e064/amqpstorm/management/queue.py#L34-L50
eandersson/amqpstorm
amqpstorm/management/queue.py
Queue.declare
def declare(self, queue='', virtual_host='/', passive=False, durable=False, auto_delete=False, arguments=None): """Declare a Queue. :param str queue: Queue name :param str virtual_host: Virtual host name :param bool passive: Do not create :param bool durable: Durable queue :param bool auto_delete: Automatically delete when not in use :param dict|None arguments: Queue key/value arguments :raises ApiError: Raises if the remote server encountered an error. :raises ApiConnectionError: Raises if there was a connectivity issue. :rtype: dict """ if passive: return self.get(queue, virtual_host=virtual_host) queue_payload = json.dumps( { 'durable': durable, 'auto_delete': auto_delete, 'arguments': arguments or {}, 'vhost': virtual_host } ) return self.http_client.put( API_QUEUE % ( quote(virtual_host, ''), queue ), payload=queue_payload)
python
def declare(self, queue='', virtual_host='/', passive=False, durable=False, auto_delete=False, arguments=None): """Declare a Queue. :param str queue: Queue name :param str virtual_host: Virtual host name :param bool passive: Do not create :param bool durable: Durable queue :param bool auto_delete: Automatically delete when not in use :param dict|None arguments: Queue key/value arguments :raises ApiError: Raises if the remote server encountered an error. :raises ApiConnectionError: Raises if there was a connectivity issue. :rtype: dict """ if passive: return self.get(queue, virtual_host=virtual_host) queue_payload = json.dumps( { 'durable': durable, 'auto_delete': auto_delete, 'arguments': arguments or {}, 'vhost': virtual_host } ) return self.http_client.put( API_QUEUE % ( quote(virtual_host, ''), queue ), payload=queue_payload)
Declare a Queue. :param str queue: Queue name :param str virtual_host: Virtual host name :param bool passive: Do not create :param bool durable: Durable queue :param bool auto_delete: Automatically delete when not in use :param dict|None arguments: Queue key/value arguments :raises ApiError: Raises if the remote server encountered an error. :raises ApiConnectionError: Raises if there was a connectivity issue. :rtype: dict
https://github.com/eandersson/amqpstorm/blob/38330906c0af19eea482f43c5ce79bab98a1e064/amqpstorm/management/queue.py#L52-L84
eandersson/amqpstorm
amqpstorm/management/queue.py
Queue.delete
def delete(self, queue, virtual_host='/'): """Delete a Queue. :param str queue: Queue name :param str virtual_host: Virtual host name :raises ApiError: Raises if the remote server encountered an error. :raises ApiConnectionError: Raises if there was a connectivity issue. :rtype: dict """ virtual_host = quote(virtual_host, '') return self.http_client.delete(API_QUEUE % ( virtual_host, queue ))
python
def delete(self, queue, virtual_host='/'): """Delete a Queue. :param str queue: Queue name :param str virtual_host: Virtual host name :raises ApiError: Raises if the remote server encountered an error. :raises ApiConnectionError: Raises if there was a connectivity issue. :rtype: dict """ virtual_host = quote(virtual_host, '') return self.http_client.delete(API_QUEUE % ( virtual_host, queue ))
Delete a Queue. :param str queue: Queue name :param str virtual_host: Virtual host name :raises ApiError: Raises if the remote server encountered an error. :raises ApiConnectionError: Raises if there was a connectivity issue. :rtype: dict
https://github.com/eandersson/amqpstorm/blob/38330906c0af19eea482f43c5ce79bab98a1e064/amqpstorm/management/queue.py#L86-L102
eandersson/amqpstorm
amqpstorm/management/queue.py
Queue.purge
def purge(self, queue, virtual_host='/'): """Purge a Queue. :param str queue: Queue name :param str virtual_host: Virtual host name :raises ApiError: Raises if the remote server encountered an error. :raises ApiConnectionError: Raises if there was a connectivity issue. :rtype: None """ virtual_host = quote(virtual_host, '') return self.http_client.delete(API_QUEUE_PURGE % ( virtual_host, queue ))
python
def purge(self, queue, virtual_host='/'): """Purge a Queue. :param str queue: Queue name :param str virtual_host: Virtual host name :raises ApiError: Raises if the remote server encountered an error. :raises ApiConnectionError: Raises if there was a connectivity issue. :rtype: None """ virtual_host = quote(virtual_host, '') return self.http_client.delete(API_QUEUE_PURGE % ( virtual_host, queue ))
Purge a Queue. :param str queue: Queue name :param str virtual_host: Virtual host name :raises ApiError: Raises if the remote server encountered an error. :raises ApiConnectionError: Raises if there was a connectivity issue. :rtype: None
https://github.com/eandersson/amqpstorm/blob/38330906c0af19eea482f43c5ce79bab98a1e064/amqpstorm/management/queue.py#L104-L120
eandersson/amqpstorm
amqpstorm/management/queue.py
Queue.bindings
def bindings(self, queue, virtual_host='/'): """Get Queue bindings. :param str queue: Queue name :param str virtual_host: Virtual host name :raises ApiError: Raises if the remote server encountered an error. :raises ApiConnectionError: Raises if there was a connectivity issue. :rtype: list """ virtual_host = quote(virtual_host, '') return self.http_client.get(API_QUEUE_BINDINGS % ( virtual_host, queue ))
python
def bindings(self, queue, virtual_host='/'): """Get Queue bindings. :param str queue: Queue name :param str virtual_host: Virtual host name :raises ApiError: Raises if the remote server encountered an error. :raises ApiConnectionError: Raises if there was a connectivity issue. :rtype: list """ virtual_host = quote(virtual_host, '') return self.http_client.get(API_QUEUE_BINDINGS % ( virtual_host, queue ))
Get Queue bindings. :param str queue: Queue name :param str virtual_host: Virtual host name :raises ApiError: Raises if the remote server encountered an error. :raises ApiConnectionError: Raises if there was a connectivity issue. :rtype: list
https://github.com/eandersson/amqpstorm/blob/38330906c0af19eea482f43c5ce79bab98a1e064/amqpstorm/management/queue.py#L122-L138
eandersson/amqpstorm
amqpstorm/management/queue.py
Queue.bind
def bind(self, queue='', exchange='', routing_key='', virtual_host='/', arguments=None): """Bind a Queue. :param str queue: Queue name :param str exchange: Exchange name :param str routing_key: The routing key to use :param str virtual_host: Virtual host name :param dict|None arguments: Bind key/value arguments :raises ApiError: Raises if the remote server encountered an error. :raises ApiConnectionError: Raises if there was a connectivity issue. :rtype: None """ bind_payload = json.dumps({ 'destination': queue, 'destination_type': 'q', 'routing_key': routing_key, 'source': exchange, 'arguments': arguments or {}, 'vhost': virtual_host }) virtual_host = quote(virtual_host, '') return self.http_client.post(API_QUEUE_BIND % ( virtual_host, exchange, queue ), payload=bind_payload)
python
def bind(self, queue='', exchange='', routing_key='', virtual_host='/', arguments=None): """Bind a Queue. :param str queue: Queue name :param str exchange: Exchange name :param str routing_key: The routing key to use :param str virtual_host: Virtual host name :param dict|None arguments: Bind key/value arguments :raises ApiError: Raises if the remote server encountered an error. :raises ApiConnectionError: Raises if there was a connectivity issue. :rtype: None """ bind_payload = json.dumps({ 'destination': queue, 'destination_type': 'q', 'routing_key': routing_key, 'source': exchange, 'arguments': arguments or {}, 'vhost': virtual_host }) virtual_host = quote(virtual_host, '') return self.http_client.post(API_QUEUE_BIND % ( virtual_host, exchange, queue ), payload=bind_payload)
Bind a Queue. :param str queue: Queue name :param str exchange: Exchange name :param str routing_key: The routing key to use :param str virtual_host: Virtual host name :param dict|None arguments: Bind key/value arguments :raises ApiError: Raises if the remote server encountered an error. :raises ApiConnectionError: Raises if there was a connectivity issue. :rtype: None
https://github.com/eandersson/amqpstorm/blob/38330906c0af19eea482f43c5ce79bab98a1e064/amqpstorm/management/queue.py#L140-L170
eandersson/amqpstorm
amqpstorm/management/queue.py
Queue.unbind
def unbind(self, queue='', exchange='', routing_key='', virtual_host='/', properties_key=None): """Unbind a Queue. :param str queue: Queue name :param str exchange: Exchange name :param str routing_key: The routing key to use :param str virtual_host: Virtual host name :param str properties_key: :raises ApiError: Raises if the remote server encountered an error. :raises ApiConnectionError: Raises if there was a connectivity issue. :rtype: None """ unbind_payload = json.dumps({ 'destination': queue, 'destination_type': 'q', 'properties_key': properties_key or routing_key, 'source': exchange, 'vhost': virtual_host }) virtual_host = quote(virtual_host, '') return self.http_client.delete(API_QUEUE_UNBIND % ( virtual_host, exchange, queue, properties_key or routing_key ), payload=unbind_payload)
python
def unbind(self, queue='', exchange='', routing_key='', virtual_host='/', properties_key=None): """Unbind a Queue. :param str queue: Queue name :param str exchange: Exchange name :param str routing_key: The routing key to use :param str virtual_host: Virtual host name :param str properties_key: :raises ApiError: Raises if the remote server encountered an error. :raises ApiConnectionError: Raises if there was a connectivity issue. :rtype: None """ unbind_payload = json.dumps({ 'destination': queue, 'destination_type': 'q', 'properties_key': properties_key or routing_key, 'source': exchange, 'vhost': virtual_host }) virtual_host = quote(virtual_host, '') return self.http_client.delete(API_QUEUE_UNBIND % ( virtual_host, exchange, queue, properties_key or routing_key ), payload=unbind_payload)
Unbind a Queue. :param str queue: Queue name :param str exchange: Exchange name :param str routing_key: The routing key to use :param str virtual_host: Virtual host name :param str properties_key: :raises ApiError: Raises if the remote server encountered an error. :raises ApiConnectionError: Raises if there was a connectivity issue. :rtype: None
https://github.com/eandersson/amqpstorm/blob/38330906c0af19eea482f43c5ce79bab98a1e064/amqpstorm/management/queue.py#L172-L202
eandersson/amqpstorm
amqpstorm/management/exchange.py
Exchange.get
def get(self, exchange, virtual_host='/'): """Get Exchange details. :param str exchange: Exchange name :param str virtual_host: Virtual host name :raises ApiError: Raises if the remote server encountered an error. :raises ApiConnectionError: Raises if there was a connectivity issue. :rtype: dict """ virtual_host = quote(virtual_host, '') return self.http_client.get( API_EXCHANGE % ( virtual_host, exchange) )
python
def get(self, exchange, virtual_host='/'): """Get Exchange details. :param str exchange: Exchange name :param str virtual_host: Virtual host name :raises ApiError: Raises if the remote server encountered an error. :raises ApiConnectionError: Raises if there was a connectivity issue. :rtype: dict """ virtual_host = quote(virtual_host, '') return self.http_client.get( API_EXCHANGE % ( virtual_host, exchange) )
Get Exchange details. :param str exchange: Exchange name :param str virtual_host: Virtual host name :raises ApiError: Raises if the remote server encountered an error. :raises ApiConnectionError: Raises if there was a connectivity issue. :rtype: dict
https://github.com/eandersson/amqpstorm/blob/38330906c0af19eea482f43c5ce79bab98a1e064/amqpstorm/management/exchange.py#L14-L31
eandersson/amqpstorm
amqpstorm/management/exchange.py
Exchange.list
def list(self, virtual_host='/', show_all=False): """List Exchanges. :param str virtual_host: Virtual host name :param bool show_all: List all Exchanges :raises ApiError: Raises if the remote server encountered an error. :raises ApiConnectionError: Raises if there was a connectivity issue. :rtype: list """ if show_all: return self.http_client.get(API_EXCHANGES) virtual_host = quote(virtual_host, '') return self.http_client.get( API_EXCHANGES_VIRTUAL_HOST % virtual_host )
python
def list(self, virtual_host='/', show_all=False): """List Exchanges. :param str virtual_host: Virtual host name :param bool show_all: List all Exchanges :raises ApiError: Raises if the remote server encountered an error. :raises ApiConnectionError: Raises if there was a connectivity issue. :rtype: list """ if show_all: return self.http_client.get(API_EXCHANGES) virtual_host = quote(virtual_host, '') return self.http_client.get( API_EXCHANGES_VIRTUAL_HOST % virtual_host )
List Exchanges. :param str virtual_host: Virtual host name :param bool show_all: List all Exchanges :raises ApiError: Raises if the remote server encountered an error. :raises ApiConnectionError: Raises if there was a connectivity issue. :rtype: list
https://github.com/eandersson/amqpstorm/blob/38330906c0af19eea482f43c5ce79bab98a1e064/amqpstorm/management/exchange.py#L33-L49
eandersson/amqpstorm
amqpstorm/management/exchange.py
Exchange.declare
def declare(self, exchange='', exchange_type='direct', virtual_host='/', passive=False, durable=False, auto_delete=False, internal=False, arguments=None): """Declare an Exchange. :param str exchange: Exchange name :param str exchange_type: Exchange type :param str virtual_host: Virtual host name :param bool passive: Do not create :param bool durable: Durable exchange :param bool auto_delete: Automatically delete when not in use :param bool internal: Is the exchange for use by the broker only. :param dict|None arguments: Exchange key/value arguments :raises ApiError: Raises if the remote server encountered an error. :raises ApiConnectionError: Raises if there was a connectivity issue. :rtype: None """ if passive: return self.get(exchange, virtual_host=virtual_host) exchange_payload = json.dumps( { 'durable': durable, 'auto_delete': auto_delete, 'internal': internal, 'type': exchange_type, 'arguments': arguments or {}, 'vhost': virtual_host } ) return self.http_client.put(API_EXCHANGE % ( quote(virtual_host, ''), exchange ), payload=exchange_payload)
python
def declare(self, exchange='', exchange_type='direct', virtual_host='/', passive=False, durable=False, auto_delete=False, internal=False, arguments=None): """Declare an Exchange. :param str exchange: Exchange name :param str exchange_type: Exchange type :param str virtual_host: Virtual host name :param bool passive: Do not create :param bool durable: Durable exchange :param bool auto_delete: Automatically delete when not in use :param bool internal: Is the exchange for use by the broker only. :param dict|None arguments: Exchange key/value arguments :raises ApiError: Raises if the remote server encountered an error. :raises ApiConnectionError: Raises if there was a connectivity issue. :rtype: None """ if passive: return self.get(exchange, virtual_host=virtual_host) exchange_payload = json.dumps( { 'durable': durable, 'auto_delete': auto_delete, 'internal': internal, 'type': exchange_type, 'arguments': arguments or {}, 'vhost': virtual_host } ) return self.http_client.put(API_EXCHANGE % ( quote(virtual_host, ''), exchange ), payload=exchange_payload)
Declare an Exchange. :param str exchange: Exchange name :param str exchange_type: Exchange type :param str virtual_host: Virtual host name :param bool passive: Do not create :param bool durable: Durable exchange :param bool auto_delete: Automatically delete when not in use :param bool internal: Is the exchange for use by the broker only. :param dict|None arguments: Exchange key/value arguments :raises ApiError: Raises if the remote server encountered an error. :raises ApiConnectionError: Raises if there was a connectivity issue. :rtype: None
https://github.com/eandersson/amqpstorm/blob/38330906c0af19eea482f43c5ce79bab98a1e064/amqpstorm/management/exchange.py#L51-L87
eandersson/amqpstorm
amqpstorm/management/exchange.py
Exchange.delete
def delete(self, exchange, virtual_host='/'): """Delete an Exchange. :param str exchange: Exchange name :param str virtual_host: Virtual host name :raises ApiError: Raises if the remote server encountered an error. :raises ApiConnectionError: Raises if there was a connectivity issue. :rtype: dict """ virtual_host = quote(virtual_host, '') return self.http_client.delete(API_EXCHANGE % ( virtual_host, exchange ))
python
def delete(self, exchange, virtual_host='/'): """Delete an Exchange. :param str exchange: Exchange name :param str virtual_host: Virtual host name :raises ApiError: Raises if the remote server encountered an error. :raises ApiConnectionError: Raises if there was a connectivity issue. :rtype: dict """ virtual_host = quote(virtual_host, '') return self.http_client.delete(API_EXCHANGE % ( virtual_host, exchange ))
Delete an Exchange. :param str exchange: Exchange name :param str virtual_host: Virtual host name :raises ApiError: Raises if the remote server encountered an error. :raises ApiConnectionError: Raises if there was a connectivity issue. :rtype: dict
https://github.com/eandersson/amqpstorm/blob/38330906c0af19eea482f43c5ce79bab98a1e064/amqpstorm/management/exchange.py#L89-L105
eandersson/amqpstorm
amqpstorm/management/exchange.py
Exchange.bindings
def bindings(self, exchange, virtual_host='/'): """Get Exchange bindings. :param str exchange: Exchange name :param str virtual_host: Virtual host name :raises ApiError: Raises if the remote server encountered an error. :raises ApiConnectionError: Raises if there was a connectivity issue. :rtype: list """ virtual_host = quote(virtual_host, '') return self.http_client.get(API_EXCHANGE_BINDINGS % ( virtual_host, exchange ))
python
def bindings(self, exchange, virtual_host='/'): """Get Exchange bindings. :param str exchange: Exchange name :param str virtual_host: Virtual host name :raises ApiError: Raises if the remote server encountered an error. :raises ApiConnectionError: Raises if there was a connectivity issue. :rtype: list """ virtual_host = quote(virtual_host, '') return self.http_client.get(API_EXCHANGE_BINDINGS % ( virtual_host, exchange ))
Get Exchange bindings. :param str exchange: Exchange name :param str virtual_host: Virtual host name :raises ApiError: Raises if the remote server encountered an error. :raises ApiConnectionError: Raises if there was a connectivity issue. :rtype: list
https://github.com/eandersson/amqpstorm/blob/38330906c0af19eea482f43c5ce79bab98a1e064/amqpstorm/management/exchange.py#L107-L123
eandersson/amqpstorm
amqpstorm/management/exchange.py
Exchange.bind
def bind(self, destination='', source='', routing_key='', virtual_host='/', arguments=None): """Bind an Exchange. :param str source: Source Exchange name :param str destination: Destination Exchange name :param str routing_key: The routing key to use :param str virtual_host: Virtual host name :param dict|None arguments: Bind key/value arguments :raises ApiError: Raises if the remote server encountered an error. :raises ApiConnectionError: Raises if there was a connectivity issue. :rtype: None """ bind_payload = json.dumps({ 'destination': destination, 'destination_type': 'e', 'routing_key': routing_key, 'source': source, 'arguments': arguments or {}, 'vhost': virtual_host }) virtual_host = quote(virtual_host, '') return self.http_client.post(API_EXCHANGE_BIND % ( virtual_host, source, destination ), payload=bind_payload)
python
def bind(self, destination='', source='', routing_key='', virtual_host='/', arguments=None): """Bind an Exchange. :param str source: Source Exchange name :param str destination: Destination Exchange name :param str routing_key: The routing key to use :param str virtual_host: Virtual host name :param dict|None arguments: Bind key/value arguments :raises ApiError: Raises if the remote server encountered an error. :raises ApiConnectionError: Raises if there was a connectivity issue. :rtype: None """ bind_payload = json.dumps({ 'destination': destination, 'destination_type': 'e', 'routing_key': routing_key, 'source': source, 'arguments': arguments or {}, 'vhost': virtual_host }) virtual_host = quote(virtual_host, '') return self.http_client.post(API_EXCHANGE_BIND % ( virtual_host, source, destination ), payload=bind_payload)
Bind an Exchange. :param str source: Source Exchange name :param str destination: Destination Exchange name :param str routing_key: The routing key to use :param str virtual_host: Virtual host name :param dict|None arguments: Bind key/value arguments :raises ApiError: Raises if the remote server encountered an error. :raises ApiConnectionError: Raises if there was a connectivity issue. :rtype: None
https://github.com/eandersson/amqpstorm/blob/38330906c0af19eea482f43c5ce79bab98a1e064/amqpstorm/management/exchange.py#L125-L155
eandersson/amqpstorm
amqpstorm/management/exchange.py
Exchange.unbind
def unbind(self, destination='', source='', routing_key='', virtual_host='/', properties_key=None): """Unbind an Exchange. :param str source: Source Exchange name :param str destination: Destination Exchange name :param str routing_key: The routing key to use :param str virtual_host: Virtual host name :param str properties_key: :raises ApiError: Raises if the remote server encountered an error. :raises ApiConnectionError: Raises if there was a connectivity issue. :rtype: None """ unbind_payload = json.dumps({ 'destination': destination, 'destination_type': 'e', 'properties_key': properties_key or routing_key, 'source': source, 'vhost': virtual_host }) virtual_host = quote(virtual_host, '') return self.http_client.delete(API_EXCHANGE_UNBIND % ( virtual_host, source, destination, properties_key or routing_key ), payload=unbind_payload)
python
def unbind(self, destination='', source='', routing_key='', virtual_host='/', properties_key=None): """Unbind an Exchange. :param str source: Source Exchange name :param str destination: Destination Exchange name :param str routing_key: The routing key to use :param str virtual_host: Virtual host name :param str properties_key: :raises ApiError: Raises if the remote server encountered an error. :raises ApiConnectionError: Raises if there was a connectivity issue. :rtype: None """ unbind_payload = json.dumps({ 'destination': destination, 'destination_type': 'e', 'properties_key': properties_key or routing_key, 'source': source, 'vhost': virtual_host }) virtual_host = quote(virtual_host, '') return self.http_client.delete(API_EXCHANGE_UNBIND % ( virtual_host, source, destination, properties_key or routing_key ), payload=unbind_payload)
Unbind an Exchange. :param str source: Source Exchange name :param str destination: Destination Exchange name :param str routing_key: The routing key to use :param str virtual_host: Virtual host name :param str properties_key: :raises ApiError: Raises if the remote server encountered an error. :raises ApiConnectionError: Raises if there was a connectivity issue. :rtype: None
https://github.com/eandersson/amqpstorm/blob/38330906c0af19eea482f43c5ce79bab98a1e064/amqpstorm/management/exchange.py#L157-L187
eandersson/amqpstorm
amqpstorm/connection.py
Connection.channel
def channel(self, rpc_timeout=60, lazy=False): """Open Channel. :param int rpc_timeout: Timeout before we give up waiting for an RPC response from the server. :raises AMQPInvalidArgument: Invalid Parameters :raises AMQPChannelError: Raises if the channel encountered an error. :raises AMQPConnectionError: Raises if the connection encountered an error. """ LOGGER.debug('Opening a new Channel') if not compatibility.is_integer(rpc_timeout): raise AMQPInvalidArgument('rpc_timeout should be an integer') elif self.is_closed: raise AMQPConnectionError('socket/connection closed') with self.lock: channel_id = self._get_next_available_channel_id() channel = Channel(channel_id, self, rpc_timeout, on_close_impl=self._cleanup_channel) self._channels[channel_id] = channel if not lazy: channel.open() LOGGER.debug('Channel #%d Opened', channel_id) return self._channels[channel_id]
python
def channel(self, rpc_timeout=60, lazy=False): """Open Channel. :param int rpc_timeout: Timeout before we give up waiting for an RPC response from the server. :raises AMQPInvalidArgument: Invalid Parameters :raises AMQPChannelError: Raises if the channel encountered an error. :raises AMQPConnectionError: Raises if the connection encountered an error. """ LOGGER.debug('Opening a new Channel') if not compatibility.is_integer(rpc_timeout): raise AMQPInvalidArgument('rpc_timeout should be an integer') elif self.is_closed: raise AMQPConnectionError('socket/connection closed') with self.lock: channel_id = self._get_next_available_channel_id() channel = Channel(channel_id, self, rpc_timeout, on_close_impl=self._cleanup_channel) self._channels[channel_id] = channel if not lazy: channel.open() LOGGER.debug('Channel #%d Opened', channel_id) return self._channels[channel_id]
Open Channel. :param int rpc_timeout: Timeout before we give up waiting for an RPC response from the server. :raises AMQPInvalidArgument: Invalid Parameters :raises AMQPChannelError: Raises if the channel encountered an error. :raises AMQPConnectionError: Raises if the connection encountered an error.
https://github.com/eandersson/amqpstorm/blob/38330906c0af19eea482f43c5ce79bab98a1e064/amqpstorm/connection.py#L145-L170
eandersson/amqpstorm
amqpstorm/connection.py
Connection.check_for_errors
def check_for_errors(self): """Check Connection for errors. :raises AMQPConnectionError: Raises if the connection encountered an error. :return: """ if not self.exceptions: if not self.is_closed: return why = AMQPConnectionError('connection was closed') self.exceptions.append(why) self.set_state(self.CLOSED) self.close() raise self.exceptions[0]
python
def check_for_errors(self): """Check Connection for errors. :raises AMQPConnectionError: Raises if the connection encountered an error. :return: """ if not self.exceptions: if not self.is_closed: return why = AMQPConnectionError('connection was closed') self.exceptions.append(why) self.set_state(self.CLOSED) self.close() raise self.exceptions[0]
Check Connection for errors. :raises AMQPConnectionError: Raises if the connection encountered an error. :return:
https://github.com/eandersson/amqpstorm/blob/38330906c0af19eea482f43c5ce79bab98a1e064/amqpstorm/connection.py#L172-L186
eandersson/amqpstorm
amqpstorm/connection.py
Connection.close
def close(self): """Close connection. :raises AMQPConnectionError: Raises if the connection encountered an error. :return: """ LOGGER.debug('Connection Closing') if not self.is_closed: self.set_state(self.CLOSING) self.heartbeat.stop() try: if not self.is_closed and self.socket: self._channel0.send_close_connection() self._wait_for_connection_state(state=Stateful.CLOSED) except AMQPConnectionError: pass finally: self._close_remaining_channels() self._io.close() self.set_state(self.CLOSED) LOGGER.debug('Connection Closed')
python
def close(self): """Close connection. :raises AMQPConnectionError: Raises if the connection encountered an error. :return: """ LOGGER.debug('Connection Closing') if not self.is_closed: self.set_state(self.CLOSING) self.heartbeat.stop() try: if not self.is_closed and self.socket: self._channel0.send_close_connection() self._wait_for_connection_state(state=Stateful.CLOSED) except AMQPConnectionError: pass finally: self._close_remaining_channels() self._io.close() self.set_state(self.CLOSED) LOGGER.debug('Connection Closed')
Close connection. :raises AMQPConnectionError: Raises if the connection encountered an error. :return:
https://github.com/eandersson/amqpstorm/blob/38330906c0af19eea482f43c5ce79bab98a1e064/amqpstorm/connection.py#L188-L209
eandersson/amqpstorm
amqpstorm/connection.py
Connection.open
def open(self): """Open Connection. :raises AMQPConnectionError: Raises if the connection encountered an error. """ LOGGER.debug('Connection Opening') self.set_state(self.OPENING) self._exceptions = [] self._channels = {} self._last_channel_id = None self._io.open() self._send_handshake() self._wait_for_connection_state(state=Stateful.OPEN) self.heartbeat.start(self._exceptions) LOGGER.debug('Connection Opened')
python
def open(self): """Open Connection. :raises AMQPConnectionError: Raises if the connection encountered an error. """ LOGGER.debug('Connection Opening') self.set_state(self.OPENING) self._exceptions = [] self._channels = {} self._last_channel_id = None self._io.open() self._send_handshake() self._wait_for_connection_state(state=Stateful.OPEN) self.heartbeat.start(self._exceptions) LOGGER.debug('Connection Opened')
Open Connection. :raises AMQPConnectionError: Raises if the connection encountered an error.
https://github.com/eandersson/amqpstorm/blob/38330906c0af19eea482f43c5ce79bab98a1e064/amqpstorm/connection.py#L211-L226
eandersson/amqpstorm
amqpstorm/connection.py
Connection.write_frame
def write_frame(self, channel_id, frame_out): """Marshal and write an outgoing pamqp frame to the Socket. :param int channel_id: Channel ID. :param specification.Frame frame_out: Amqp frame. :return: """ frame_data = pamqp_frame.marshal(frame_out, channel_id) self.heartbeat.register_write() self._io.write_to_socket(frame_data)
python
def write_frame(self, channel_id, frame_out): """Marshal and write an outgoing pamqp frame to the Socket. :param int channel_id: Channel ID. :param specification.Frame frame_out: Amqp frame. :return: """ frame_data = pamqp_frame.marshal(frame_out, channel_id) self.heartbeat.register_write() self._io.write_to_socket(frame_data)
Marshal and write an outgoing pamqp frame to the Socket. :param int channel_id: Channel ID. :param specification.Frame frame_out: Amqp frame. :return:
https://github.com/eandersson/amqpstorm/blob/38330906c0af19eea482f43c5ce79bab98a1e064/amqpstorm/connection.py#L228-L238
eandersson/amqpstorm
amqpstorm/connection.py
Connection.write_frames
def write_frames(self, channel_id, frames_out): """Marshal and write multiple outgoing pamqp frames to the Socket. :param int channel_id: Channel ID/ :param list frames_out: Amqp frames. :return: """ data_out = EMPTY_BUFFER for single_frame in frames_out: data_out += pamqp_frame.marshal(single_frame, channel_id) self.heartbeat.register_write() self._io.write_to_socket(data_out)
python
def write_frames(self, channel_id, frames_out): """Marshal and write multiple outgoing pamqp frames to the Socket. :param int channel_id: Channel ID/ :param list frames_out: Amqp frames. :return: """ data_out = EMPTY_BUFFER for single_frame in frames_out: data_out += pamqp_frame.marshal(single_frame, channel_id) self.heartbeat.register_write() self._io.write_to_socket(data_out)
Marshal and write multiple outgoing pamqp frames to the Socket. :param int channel_id: Channel ID/ :param list frames_out: Amqp frames. :return:
https://github.com/eandersson/amqpstorm/blob/38330906c0af19eea482f43c5ce79bab98a1e064/amqpstorm/connection.py#L240-L252
eandersson/amqpstorm
amqpstorm/connection.py
Connection._close_remaining_channels
def _close_remaining_channels(self): """Forcefully close all open channels. :return: """ for channel_id in list(self._channels): self._channels[channel_id].set_state(Channel.CLOSED) self._channels[channel_id].close() self._cleanup_channel(channel_id)
python
def _close_remaining_channels(self): """Forcefully close all open channels. :return: """ for channel_id in list(self._channels): self._channels[channel_id].set_state(Channel.CLOSED) self._channels[channel_id].close() self._cleanup_channel(channel_id)
Forcefully close all open channels. :return:
https://github.com/eandersson/amqpstorm/blob/38330906c0af19eea482f43c5ce79bab98a1e064/amqpstorm/connection.py#L254-L262
eandersson/amqpstorm
amqpstorm/connection.py
Connection._get_next_available_channel_id
def _get_next_available_channel_id(self): """Returns the next available available channel id. :raises AMQPConnectionError: Raises if there is no available channel. :rtype: int """ for index in compatibility.RANGE(self._last_channel_id or 1, self.max_allowed_channels + 1): if index in self._channels: continue self._last_channel_id = index return index if self._last_channel_id: self._last_channel_id = None return self._get_next_available_channel_id() raise AMQPConnectionError( 'reached the maximum number of channels %d' % self.max_allowed_channels)
python
def _get_next_available_channel_id(self): """Returns the next available available channel id. :raises AMQPConnectionError: Raises if there is no available channel. :rtype: int """ for index in compatibility.RANGE(self._last_channel_id or 1, self.max_allowed_channels + 1): if index in self._channels: continue self._last_channel_id = index return index if self._last_channel_id: self._last_channel_id = None return self._get_next_available_channel_id() raise AMQPConnectionError( 'reached the maximum number of channels %d' % self.max_allowed_channels)
Returns the next available available channel id. :raises AMQPConnectionError: Raises if there is no available channel. :rtype: int
https://github.com/eandersson/amqpstorm/blob/38330906c0af19eea482f43c5ce79bab98a1e064/amqpstorm/connection.py#L264-L282
eandersson/amqpstorm
amqpstorm/connection.py
Connection._handle_amqp_frame
def _handle_amqp_frame(self, data_in): """Unmarshal a single AMQP frame and return the result. :param data_in: socket data :return: data_in, channel_id, frame """ if not data_in: return data_in, None, None try: byte_count, channel_id, frame_in = pamqp_frame.unmarshal(data_in) return data_in[byte_count:], channel_id, frame_in except pamqp_exception.UnmarshalingException: pass except specification.AMQPFrameError as why: LOGGER.error('AMQPFrameError: %r', why, exc_info=True) except ValueError as why: LOGGER.error(why, exc_info=True) self.exceptions.append(AMQPConnectionError(why)) return data_in, None, None
python
def _handle_amqp_frame(self, data_in): """Unmarshal a single AMQP frame and return the result. :param data_in: socket data :return: data_in, channel_id, frame """ if not data_in: return data_in, None, None try: byte_count, channel_id, frame_in = pamqp_frame.unmarshal(data_in) return data_in[byte_count:], channel_id, frame_in except pamqp_exception.UnmarshalingException: pass except specification.AMQPFrameError as why: LOGGER.error('AMQPFrameError: %r', why, exc_info=True) except ValueError as why: LOGGER.error(why, exc_info=True) self.exceptions.append(AMQPConnectionError(why)) return data_in, None, None
Unmarshal a single AMQP frame and return the result. :param data_in: socket data :return: data_in, channel_id, frame
https://github.com/eandersson/amqpstorm/blob/38330906c0af19eea482f43c5ce79bab98a1e064/amqpstorm/connection.py#L284-L303
eandersson/amqpstorm
amqpstorm/connection.py
Connection._read_buffer
def _read_buffer(self, data_in): """Process the socket buffer, and direct the data to the appropriate channel. :rtype: bytes """ while data_in: data_in, channel_id, frame_in = self._handle_amqp_frame(data_in) if frame_in is None: break self.heartbeat.register_read() if channel_id == 0: self._channel0.on_frame(frame_in) elif channel_id in self._channels: self._channels[channel_id].on_frame(frame_in) return data_in
python
def _read_buffer(self, data_in): """Process the socket buffer, and direct the data to the appropriate channel. :rtype: bytes """ while data_in: data_in, channel_id, frame_in = self._handle_amqp_frame(data_in) if frame_in is None: break self.heartbeat.register_read() if channel_id == 0: self._channel0.on_frame(frame_in) elif channel_id in self._channels: self._channels[channel_id].on_frame(frame_in) return data_in
Process the socket buffer, and direct the data to the appropriate channel. :rtype: bytes
https://github.com/eandersson/amqpstorm/blob/38330906c0af19eea482f43c5ce79bab98a1e064/amqpstorm/connection.py#L305-L323
eandersson/amqpstorm
amqpstorm/connection.py
Connection._cleanup_channel
def _cleanup_channel(self, channel_id): """Remove the the channel from the list of available channels. :param int channel_id: Channel id :return: """ with self.lock: if channel_id not in self._channels: return del self._channels[channel_id]
python
def _cleanup_channel(self, channel_id): """Remove the the channel from the list of available channels. :param int channel_id: Channel id :return: """ with self.lock: if channel_id not in self._channels: return del self._channels[channel_id]
Remove the the channel from the list of available channels. :param int channel_id: Channel id :return:
https://github.com/eandersson/amqpstorm/blob/38330906c0af19eea482f43c5ce79bab98a1e064/amqpstorm/connection.py#L325-L335
eandersson/amqpstorm
amqpstorm/connection.py
Connection._validate_parameters
def _validate_parameters(self): """Validate Connection Parameters. :return: """ if not compatibility.is_string(self.parameters['hostname']): raise AMQPInvalidArgument('hostname should be a string') elif not compatibility.is_integer(self.parameters['port']): raise AMQPInvalidArgument('port should be an integer') elif not compatibility.is_string(self.parameters['username']): raise AMQPInvalidArgument('username should be a string') elif not compatibility.is_string(self.parameters['password']): raise AMQPInvalidArgument('password should be a string') elif not compatibility.is_string(self.parameters['virtual_host']): raise AMQPInvalidArgument('virtual_host should be a string') elif not isinstance(self.parameters['timeout'], (int, float)): raise AMQPInvalidArgument('timeout should be an integer or float') elif not compatibility.is_integer(self.parameters['heartbeat']): raise AMQPInvalidArgument('heartbeat should be an integer')
python
def _validate_parameters(self): """Validate Connection Parameters. :return: """ if not compatibility.is_string(self.parameters['hostname']): raise AMQPInvalidArgument('hostname should be a string') elif not compatibility.is_integer(self.parameters['port']): raise AMQPInvalidArgument('port should be an integer') elif not compatibility.is_string(self.parameters['username']): raise AMQPInvalidArgument('username should be a string') elif not compatibility.is_string(self.parameters['password']): raise AMQPInvalidArgument('password should be a string') elif not compatibility.is_string(self.parameters['virtual_host']): raise AMQPInvalidArgument('virtual_host should be a string') elif not isinstance(self.parameters['timeout'], (int, float)): raise AMQPInvalidArgument('timeout should be an integer or float') elif not compatibility.is_integer(self.parameters['heartbeat']): raise AMQPInvalidArgument('heartbeat should be an integer')
Validate Connection Parameters. :return:
https://github.com/eandersson/amqpstorm/blob/38330906c0af19eea482f43c5ce79bab98a1e064/amqpstorm/connection.py#L344-L362
eandersson/amqpstorm
amqpstorm/connection.py
Connection._wait_for_connection_state
def _wait_for_connection_state(self, state=Stateful.OPEN, rpc_timeout=30): """Wait for a Connection state. :param int state: State that we expect :raises AMQPConnectionError: Raises if we are unable to establish a connection to RabbitMQ. :return: """ start_time = time.time() while self.current_state != state: self.check_for_errors() if time.time() - start_time > rpc_timeout: raise AMQPConnectionError('Connection timed out') sleep(IDLE_WAIT)
python
def _wait_for_connection_state(self, state=Stateful.OPEN, rpc_timeout=30): """Wait for a Connection state. :param int state: State that we expect :raises AMQPConnectionError: Raises if we are unable to establish a connection to RabbitMQ. :return: """ start_time = time.time() while self.current_state != state: self.check_for_errors() if time.time() - start_time > rpc_timeout: raise AMQPConnectionError('Connection timed out') sleep(IDLE_WAIT)
Wait for a Connection state. :param int state: State that we expect :raises AMQPConnectionError: Raises if we are unable to establish a connection to RabbitMQ. :return:
https://github.com/eandersson/amqpstorm/blob/38330906c0af19eea482f43c5ce79bab98a1e064/amqpstorm/connection.py#L364-L379
eandersson/amqpstorm
examples/robust_consumer.py
Consumer.create_connection
def create_connection(self): """Create a connection. :return: """ attempts = 0 while True: attempts += 1 try: self.connection = Connection('127.0.0.1', 'guest', 'guest') break except amqpstorm.AMQPError as why: LOGGER.exception(why) if self.max_retries and attempts > self.max_retries: break time.sleep(min(attempts * 2, 30)) except KeyboardInterrupt: break
python
def create_connection(self): """Create a connection. :return: """ attempts = 0 while True: attempts += 1 try: self.connection = Connection('127.0.0.1', 'guest', 'guest') break except amqpstorm.AMQPError as why: LOGGER.exception(why) if self.max_retries and attempts > self.max_retries: break time.sleep(min(attempts * 2, 30)) except KeyboardInterrupt: break
Create a connection. :return:
https://github.com/eandersson/amqpstorm/blob/38330906c0af19eea482f43c5ce79bab98a1e064/examples/robust_consumer.py#L20-L37
eandersson/amqpstorm
examples/robust_consumer.py
Consumer.start
def start(self): """Start the Consumers. :return: """ if not self.connection: self.create_connection() while True: try: channel = self.connection.channel() channel.queue.declare('simple_queue') channel.basic.consume(self, 'simple_queue', no_ack=False) channel.start_consuming() if not channel.consumer_tags: channel.close() except amqpstorm.AMQPError as why: LOGGER.exception(why) self.create_connection() except KeyboardInterrupt: self.connection.close() break
python
def start(self): """Start the Consumers. :return: """ if not self.connection: self.create_connection() while True: try: channel = self.connection.channel() channel.queue.declare('simple_queue') channel.basic.consume(self, 'simple_queue', no_ack=False) channel.start_consuming() if not channel.consumer_tags: channel.close() except amqpstorm.AMQPError as why: LOGGER.exception(why) self.create_connection() except KeyboardInterrupt: self.connection.close() break
Start the Consumers. :return:
https://github.com/eandersson/amqpstorm/blob/38330906c0af19eea482f43c5ce79bab98a1e064/examples/robust_consumer.py#L39-L59
eandersson/amqpstorm
examples/scalable_consumer.py
ScalableConsumer.stop
def stop(self): """Stop all consumers. :return: """ while self._consumers: consumer = self._consumers.pop() consumer.stop() self._stopped.set() self._connection.close()
python
def stop(self): """Stop all consumers. :return: """ while self._consumers: consumer = self._consumers.pop() consumer.stop() self._stopped.set() self._connection.close()
Stop all consumers. :return:
https://github.com/eandersson/amqpstorm/blob/38330906c0af19eea482f43c5ce79bab98a1e064/examples/scalable_consumer.py#L69-L78
eandersson/amqpstorm
examples/scalable_consumer.py
ScalableConsumer._create_connection
def _create_connection(self): """Create a connection. :return: """ attempts = 0 while True: attempts += 1 if self._stopped.is_set(): break try: self._connection = Connection(self.hostname, self.username, self.password) break except amqpstorm.AMQPError as why: LOGGER.warning(why) if self.max_retries and attempts > self.max_retries: raise Exception('max number of retries reached') time.sleep(min(attempts * 2, 30)) except KeyboardInterrupt: break
python
def _create_connection(self): """Create a connection. :return: """ attempts = 0 while True: attempts += 1 if self._stopped.is_set(): break try: self._connection = Connection(self.hostname, self.username, self.password) break except amqpstorm.AMQPError as why: LOGGER.warning(why) if self.max_retries and attempts > self.max_retries: raise Exception('max number of retries reached') time.sleep(min(attempts * 2, 30)) except KeyboardInterrupt: break
Create a connection. :return:
https://github.com/eandersson/amqpstorm/blob/38330906c0af19eea482f43c5ce79bab98a1e064/examples/scalable_consumer.py#L80-L101
eandersson/amqpstorm
examples/scalable_consumer.py
ScalableConsumer._stop_consumers
def _stop_consumers(self, number_of_consumers=0): """Stop a specific number of consumers. :param number_of_consumers: :return: """ while len(self._consumers) > number_of_consumers: consumer = self._consumers.pop() consumer.stop()
python
def _stop_consumers(self, number_of_consumers=0): """Stop a specific number of consumers. :param number_of_consumers: :return: """ while len(self._consumers) > number_of_consumers: consumer = self._consumers.pop() consumer.stop()
Stop a specific number of consumers. :param number_of_consumers: :return:
https://github.com/eandersson/amqpstorm/blob/38330906c0af19eea482f43c5ce79bab98a1e064/examples/scalable_consumer.py#L131-L139
eandersson/amqpstorm
examples/scalable_consumer.py
ScalableConsumer._start_consumer
def _start_consumer(self, consumer): """Start a consumer as a new Thread. :param Consumer consumer: :return: """ thread = threading.Thread(target=consumer.start, args=(self._connection,)) thread.daemon = True thread.start()
python
def _start_consumer(self, consumer): """Start a consumer as a new Thread. :param Consumer consumer: :return: """ thread = threading.Thread(target=consumer.start, args=(self._connection,)) thread.daemon = True thread.start()
Start a consumer as a new Thread. :param Consumer consumer: :return:
https://github.com/eandersson/amqpstorm/blob/38330906c0af19eea482f43c5ce79bab98a1e064/examples/scalable_consumer.py#L141-L150
eandersson/amqpstorm
amqpstorm/tx.py
Tx.select
def select(self): """Enable standard transaction mode. This will enable transaction mode on the channel. Meaning that messages will be kept in the remote server buffer until such a time that either commit or rollback is called. :return: """ self._tx_active = True return self._channel.rpc_request(specification.Tx.Select())
python
def select(self): """Enable standard transaction mode. This will enable transaction mode on the channel. Meaning that messages will be kept in the remote server buffer until such a time that either commit or rollback is called. :return: """ self._tx_active = True return self._channel.rpc_request(specification.Tx.Select())
Enable standard transaction mode. This will enable transaction mode on the channel. Meaning that messages will be kept in the remote server buffer until such a time that either commit or rollback is called. :return:
https://github.com/eandersson/amqpstorm/blob/38330906c0af19eea482f43c5ce79bab98a1e064/amqpstorm/tx.py#L41-L51
eandersson/amqpstorm
amqpstorm/tx.py
Tx.commit
def commit(self): """Commit the current transaction. Commit all messages published during the current transaction session to the remote server. A new transaction session starts as soon as the command has been executed. :return: """ self._tx_active = False return self._channel.rpc_request(specification.Tx.Commit())
python
def commit(self): """Commit the current transaction. Commit all messages published during the current transaction session to the remote server. A new transaction session starts as soon as the command has been executed. :return: """ self._tx_active = False return self._channel.rpc_request(specification.Tx.Commit())
Commit the current transaction. Commit all messages published during the current transaction session to the remote server. A new transaction session starts as soon as the command has been executed. :return:
https://github.com/eandersson/amqpstorm/blob/38330906c0af19eea482f43c5ce79bab98a1e064/amqpstorm/tx.py#L53-L65
eandersson/amqpstorm
amqpstorm/tx.py
Tx.rollback
def rollback(self): """Abandon the current transaction. Rollback all messages published during the current transaction session to the remote server. Note that all messages published during this transaction session will be lost, and will have to be published again. A new transaction session starts as soon as the command has been executed. :return: """ self._tx_active = False return self._channel.rpc_request(specification.Tx.Rollback())
python
def rollback(self): """Abandon the current transaction. Rollback all messages published during the current transaction session to the remote server. Note that all messages published during this transaction session will be lost, and will have to be published again. A new transaction session starts as soon as the command has been executed. :return: """ self._tx_active = False return self._channel.rpc_request(specification.Tx.Rollback())
Abandon the current transaction. Rollback all messages published during the current transaction session to the remote server. Note that all messages published during this transaction session will be lost, and will have to be published again. A new transaction session starts as soon as the command has been executed. :return:
https://github.com/eandersson/amqpstorm/blob/38330906c0af19eea482f43c5ce79bab98a1e064/amqpstorm/tx.py#L67-L82
eandersson/amqpstorm
examples/flask_threaded_rpc_client.py
rpc_call
def rpc_call(payload): """Simple Flask implementation for making asynchronous Rpc calls. """ # Send the request and store the requests Unique ID. corr_id = RPC_CLIENT.send_request(payload) # Wait until we have received a response. while RPC_CLIENT.queue[corr_id] is None: sleep(0.1) # Return the response to the user. return RPC_CLIENT.queue[corr_id]
python
def rpc_call(payload): """Simple Flask implementation for making asynchronous Rpc calls. """ # Send the request and store the requests Unique ID. corr_id = RPC_CLIENT.send_request(payload) # Wait until we have received a response. while RPC_CLIENT.queue[corr_id] is None: sleep(0.1) # Return the response to the user. return RPC_CLIENT.queue[corr_id]
Simple Flask implementation for making asynchronous Rpc calls.
https://github.com/eandersson/amqpstorm/blob/38330906c0af19eea482f43c5ce79bab98a1e064/examples/flask_threaded_rpc_client.py#L73-L84
eandersson/amqpstorm
examples/flask_threaded_rpc_client.py
RpcClient._create_process_thread
def _create_process_thread(self): """Create a thread responsible for consuming messages in response to RPC requests. """ thread = threading.Thread(target=self._process_data_events) thread.setDaemon(True) thread.start()
python
def _create_process_thread(self): """Create a thread responsible for consuming messages in response to RPC requests. """ thread = threading.Thread(target=self._process_data_events) thread.setDaemon(True) thread.start()
Create a thread responsible for consuming messages in response to RPC requests.
https://github.com/eandersson/amqpstorm/blob/38330906c0af19eea482f43c5ce79bab98a1e064/examples/flask_threaded_rpc_client.py#L38-L44
eandersson/amqpstorm
amqpstorm/message.py
Message.create
def create(channel, body, properties=None): """Create a new Message. :param Channel channel: AMQPStorm Channel :param bytes|str|unicode body: Message payload :param dict properties: Message properties :rtype: Message """ properties = properties or {} if 'correlation_id' not in properties: properties['correlation_id'] = str(uuid.uuid4()) if 'message_id' not in properties: properties['message_id'] = str(uuid.uuid4()) if 'timestamp' not in properties: properties['timestamp'] = datetime.utcnow() return Message(channel, auto_decode=False, body=body, properties=properties)
python
def create(channel, body, properties=None): """Create a new Message. :param Channel channel: AMQPStorm Channel :param bytes|str|unicode body: Message payload :param dict properties: Message properties :rtype: Message """ properties = properties or {} if 'correlation_id' not in properties: properties['correlation_id'] = str(uuid.uuid4()) if 'message_id' not in properties: properties['message_id'] = str(uuid.uuid4()) if 'timestamp' not in properties: properties['timestamp'] = datetime.utcnow() return Message(channel, auto_decode=False, body=body, properties=properties)
Create a new Message. :param Channel channel: AMQPStorm Channel :param bytes|str|unicode body: Message payload :param dict properties: Message properties :rtype: Message
https://github.com/eandersson/amqpstorm/blob/38330906c0af19eea482f43c5ce79bab98a1e064/amqpstorm/message.py#L32-L50
eandersson/amqpstorm
amqpstorm/message.py
Message.body
def body(self): """Return the Message Body. If auto_decode is enabled, the body will automatically be decoded using decode('utf-8') if possible. :rtype: bytes|str|unicode """ if not self._auto_decode: return self._body if 'body' in self._decode_cache: return self._decode_cache['body'] body = try_utf8_decode(self._body) self._decode_cache['body'] = body return body
python
def body(self): """Return the Message Body. If auto_decode is enabled, the body will automatically be decoded using decode('utf-8') if possible. :rtype: bytes|str|unicode """ if not self._auto_decode: return self._body if 'body' in self._decode_cache: return self._decode_cache['body'] body = try_utf8_decode(self._body) self._decode_cache['body'] = body return body
Return the Message Body. If auto_decode is enabled, the body will automatically be decoded using decode('utf-8') if possible. :rtype: bytes|str|unicode
https://github.com/eandersson/amqpstorm/blob/38330906c0af19eea482f43c5ce79bab98a1e064/amqpstorm/message.py#L53-L67
eandersson/amqpstorm
amqpstorm/message.py
Message.ack
def ack(self): """Acknowledge Message. :raises AMQPInvalidArgument: Invalid Parameters :raises AMQPChannelError: Raises if the channel encountered an error. :raises AMQPConnectionError: Raises if the connection encountered an error. :return: """ if not self._method: raise AMQPMessageError( 'Message.ack only available on incoming messages' ) self._channel.basic.ack(delivery_tag=self.delivery_tag)
python
def ack(self): """Acknowledge Message. :raises AMQPInvalidArgument: Invalid Parameters :raises AMQPChannelError: Raises if the channel encountered an error. :raises AMQPConnectionError: Raises if the connection encountered an error. :return: """ if not self._method: raise AMQPMessageError( 'Message.ack only available on incoming messages' ) self._channel.basic.ack(delivery_tag=self.delivery_tag)
Acknowledge Message. :raises AMQPInvalidArgument: Invalid Parameters :raises AMQPChannelError: Raises if the channel encountered an error. :raises AMQPConnectionError: Raises if the connection encountered an error. :return:
https://github.com/eandersson/amqpstorm/blob/38330906c0af19eea482f43c5ce79bab98a1e064/amqpstorm/message.py#L99-L113
eandersson/amqpstorm
amqpstorm/message.py
Message.nack
def nack(self, requeue=True): """Negative Acknowledgement. :raises AMQPInvalidArgument: Invalid Parameters :raises AMQPChannelError: Raises if the channel encountered an error. :raises AMQPConnectionError: Raises if the connection encountered an error. :param bool requeue: Re-queue the message """ if not self._method: raise AMQPMessageError( 'Message.nack only available on incoming messages' ) self._channel.basic.nack(delivery_tag=self.delivery_tag, requeue=requeue)
python
def nack(self, requeue=True): """Negative Acknowledgement. :raises AMQPInvalidArgument: Invalid Parameters :raises AMQPChannelError: Raises if the channel encountered an error. :raises AMQPConnectionError: Raises if the connection encountered an error. :param bool requeue: Re-queue the message """ if not self._method: raise AMQPMessageError( 'Message.nack only available on incoming messages' ) self._channel.basic.nack(delivery_tag=self.delivery_tag, requeue=requeue)
Negative Acknowledgement. :raises AMQPInvalidArgument: Invalid Parameters :raises AMQPChannelError: Raises if the channel encountered an error. :raises AMQPConnectionError: Raises if the connection encountered an error. :param bool requeue: Re-queue the message
https://github.com/eandersson/amqpstorm/blob/38330906c0af19eea482f43c5ce79bab98a1e064/amqpstorm/message.py#L115-L130
eandersson/amqpstorm
amqpstorm/message.py
Message.publish
def publish(self, routing_key, exchange='', mandatory=False, immediate=False): """Publish Message. :param str routing_key: Message routing key :param str exchange: The exchange to publish the message to :param bool mandatory: Requires the message is published :param bool immediate: Request immediate delivery :raises AMQPInvalidArgument: Invalid Parameters :raises AMQPChannelError: Raises if the channel encountered an error. :raises AMQPConnectionError: Raises if the connection encountered an error. :rtype: bool|None """ return self._channel.basic.publish(body=self._body, routing_key=routing_key, exchange=exchange, properties=self._properties, mandatory=mandatory, immediate=immediate)
python
def publish(self, routing_key, exchange='', mandatory=False, immediate=False): """Publish Message. :param str routing_key: Message routing key :param str exchange: The exchange to publish the message to :param bool mandatory: Requires the message is published :param bool immediate: Request immediate delivery :raises AMQPInvalidArgument: Invalid Parameters :raises AMQPChannelError: Raises if the channel encountered an error. :raises AMQPConnectionError: Raises if the connection encountered an error. :rtype: bool|None """ return self._channel.basic.publish(body=self._body, routing_key=routing_key, exchange=exchange, properties=self._properties, mandatory=mandatory, immediate=immediate)
Publish Message. :param str routing_key: Message routing key :param str exchange: The exchange to publish the message to :param bool mandatory: Requires the message is published :param bool immediate: Request immediate delivery :raises AMQPInvalidArgument: Invalid Parameters :raises AMQPChannelError: Raises if the channel encountered an error. :raises AMQPConnectionError: Raises if the connection encountered an error. :rtype: bool|None
https://github.com/eandersson/amqpstorm/blob/38330906c0af19eea482f43c5ce79bab98a1e064/amqpstorm/message.py#L149-L170
eandersson/amqpstorm
amqpstorm/message.py
Message._update_properties
def _update_properties(self, name, value): """Update properties, and keep cache up-to-date if auto decode is enabled. :param str name: Key :param obj value: Value :return: """ if self._auto_decode and 'properties' in self._decode_cache: self._decode_cache['properties'][name] = value self._properties[name] = value
python
def _update_properties(self, name, value): """Update properties, and keep cache up-to-date if auto decode is enabled. :param str name: Key :param obj value: Value :return: """ if self._auto_decode and 'properties' in self._decode_cache: self._decode_cache['properties'][name] = value self._properties[name] = value
Update properties, and keep cache up-to-date if auto decode is enabled. :param str name: Key :param obj value: Value :return:
https://github.com/eandersson/amqpstorm/blob/38330906c0af19eea482f43c5ce79bab98a1e064/amqpstorm/message.py#L344-L354
eandersson/amqpstorm
amqpstorm/message.py
Message._try_decode_utf8_content
def _try_decode_utf8_content(self, content, content_type): """Generic function to decode content. :param object content: :return: """ if not self._auto_decode or not content: return content if content_type in self._decode_cache: return self._decode_cache[content_type] if isinstance(content, dict): content = self._try_decode_dict(content) else: content = try_utf8_decode(content) self._decode_cache[content_type] = content return content
python
def _try_decode_utf8_content(self, content, content_type): """Generic function to decode content. :param object content: :return: """ if not self._auto_decode or not content: return content if content_type in self._decode_cache: return self._decode_cache[content_type] if isinstance(content, dict): content = self._try_decode_dict(content) else: content = try_utf8_decode(content) self._decode_cache[content_type] = content return content
Generic function to decode content. :param object content: :return:
https://github.com/eandersson/amqpstorm/blob/38330906c0af19eea482f43c5ce79bab98a1e064/amqpstorm/message.py#L356-L371
eandersson/amqpstorm
amqpstorm/message.py
Message._try_decode_dict
def _try_decode_dict(self, content): """Decode content of a dictionary. :param dict content: :return: """ result = dict() for key, value in content.items(): key = try_utf8_decode(key) if isinstance(value, dict): result[key] = self._try_decode_dict(value) elif isinstance(value, list): result[key] = self._try_decode_list(value) elif isinstance(value, tuple): result[key] = self._try_decode_tuple(value) else: result[key] = try_utf8_decode(value) return result
python
def _try_decode_dict(self, content): """Decode content of a dictionary. :param dict content: :return: """ result = dict() for key, value in content.items(): key = try_utf8_decode(key) if isinstance(value, dict): result[key] = self._try_decode_dict(value) elif isinstance(value, list): result[key] = self._try_decode_list(value) elif isinstance(value, tuple): result[key] = self._try_decode_tuple(value) else: result[key] = try_utf8_decode(value) return result
Decode content of a dictionary. :param dict content: :return:
https://github.com/eandersson/amqpstorm/blob/38330906c0af19eea482f43c5ce79bab98a1e064/amqpstorm/message.py#L373-L390
eandersson/amqpstorm
amqpstorm/message.py
Message._try_decode_list
def _try_decode_list(content): """Decode content of a list. :param list|tuple content: :return: """ result = list() for value in content: result.append(try_utf8_decode(value)) return result
python
def _try_decode_list(content): """Decode content of a list. :param list|tuple content: :return: """ result = list() for value in content: result.append(try_utf8_decode(value)) return result
Decode content of a list. :param list|tuple content: :return:
https://github.com/eandersson/amqpstorm/blob/38330906c0af19eea482f43c5ce79bab98a1e064/amqpstorm/message.py#L393-L402
eandersson/amqpstorm
amqpstorm/management/basic.py
Basic.publish
def publish(self, body, routing_key, exchange='amq.default', virtual_host='/', properties=None, payload_encoding='string'): """Publish a Message. :param bytes|str|unicode body: Message payload :param str routing_key: Message routing key :param str exchange: The exchange to publish the message to :param str virtual_host: Virtual host name :param dict properties: Message properties :param str payload_encoding: Payload encoding. :raises ApiError: Raises if the remote server encountered an error. :raises ApiConnectionError: Raises if there was a connectivity issue. :rtype: dict """ exchange = quote(exchange, '') properties = properties or {} body = json.dumps( { 'routing_key': routing_key, 'payload': body, 'payload_encoding': payload_encoding, 'properties': properties, 'vhost': virtual_host } ) virtual_host = quote(virtual_host, '') return self.http_client.post(API_BASIC_PUBLISH % ( virtual_host, exchange), payload=body)
python
def publish(self, body, routing_key, exchange='amq.default', virtual_host='/', properties=None, payload_encoding='string'): """Publish a Message. :param bytes|str|unicode body: Message payload :param str routing_key: Message routing key :param str exchange: The exchange to publish the message to :param str virtual_host: Virtual host name :param dict properties: Message properties :param str payload_encoding: Payload encoding. :raises ApiError: Raises if the remote server encountered an error. :raises ApiConnectionError: Raises if there was a connectivity issue. :rtype: dict """ exchange = quote(exchange, '') properties = properties or {} body = json.dumps( { 'routing_key': routing_key, 'payload': body, 'payload_encoding': payload_encoding, 'properties': properties, 'vhost': virtual_host } ) virtual_host = quote(virtual_host, '') return self.http_client.post(API_BASIC_PUBLISH % ( virtual_host, exchange), payload=body)
Publish a Message. :param bytes|str|unicode body: Message payload :param str routing_key: Message routing key :param str exchange: The exchange to publish the message to :param str virtual_host: Virtual host name :param dict properties: Message properties :param str payload_encoding: Payload encoding. :raises ApiError: Raises if the remote server encountered an error. :raises ApiConnectionError: Raises if there was a connectivity issue. :rtype: dict
https://github.com/eandersson/amqpstorm/blob/38330906c0af19eea482f43c5ce79bab98a1e064/amqpstorm/management/basic.py#L11-L43
eandersson/amqpstorm
amqpstorm/management/basic.py
Basic.get
def get(self, queue, virtual_host='/', requeue=False, to_dict=False, count=1, truncate=50000, encoding='auto'): """Get Messages. :param str queue: Queue name :param str virtual_host: Virtual host name :param bool requeue: Re-queue message :param bool to_dict: Should incoming messages be converted to a dictionary before delivery. :param int count: How many messages should we try to fetch. :param int truncate: The maximum length in bytes, beyond that the server will truncate the message. :param str encoding: Message encoding. :raises ApiError: Raises if the remote server encountered an error. :raises ApiConnectionError: Raises if there was a connectivity issue. :rtype: list """ ackmode = 'ack_requeue_false' if requeue: ackmode = 'ack_requeue_true' get_messages = json.dumps( { 'count': count, 'requeue': requeue, 'ackmode': ackmode, 'encoding': encoding, 'truncate': truncate, 'vhost': virtual_host } ) virtual_host = quote(virtual_host, '') response = self.http_client.post(API_BASIC_GET_MESSAGE % ( virtual_host, queue ), payload=get_messages) if to_dict: return response messages = [] for message in response: if 'payload' in message: message['body'] = message.pop('payload') messages.append(Message(channel=None, auto_decode=True, **message)) return messages
python
def get(self, queue, virtual_host='/', requeue=False, to_dict=False, count=1, truncate=50000, encoding='auto'): """Get Messages. :param str queue: Queue name :param str virtual_host: Virtual host name :param bool requeue: Re-queue message :param bool to_dict: Should incoming messages be converted to a dictionary before delivery. :param int count: How many messages should we try to fetch. :param int truncate: The maximum length in bytes, beyond that the server will truncate the message. :param str encoding: Message encoding. :raises ApiError: Raises if the remote server encountered an error. :raises ApiConnectionError: Raises if there was a connectivity issue. :rtype: list """ ackmode = 'ack_requeue_false' if requeue: ackmode = 'ack_requeue_true' get_messages = json.dumps( { 'count': count, 'requeue': requeue, 'ackmode': ackmode, 'encoding': encoding, 'truncate': truncate, 'vhost': virtual_host } ) virtual_host = quote(virtual_host, '') response = self.http_client.post(API_BASIC_GET_MESSAGE % ( virtual_host, queue ), payload=get_messages) if to_dict: return response messages = [] for message in response: if 'payload' in message: message['body'] = message.pop('payload') messages.append(Message(channel=None, auto_decode=True, **message)) return messages
Get Messages. :param str queue: Queue name :param str virtual_host: Virtual host name :param bool requeue: Re-queue message :param bool to_dict: Should incoming messages be converted to a dictionary before delivery. :param int count: How many messages should we try to fetch. :param int truncate: The maximum length in bytes, beyond that the server will truncate the message. :param str encoding: Message encoding. :raises ApiError: Raises if the remote server encountered an error. :raises ApiConnectionError: Raises if there was a connectivity issue. :rtype: list
https://github.com/eandersson/amqpstorm/blob/38330906c0af19eea482f43c5ce79bab98a1e064/amqpstorm/management/basic.py#L45-L92
eandersson/amqpstorm
amqpstorm/management/virtual_host.py
VirtualHost.get
def get(self, virtual_host): """Get Virtual Host details. :param str virtual_host: Virtual host name :raises ApiError: Raises if the remote server encountered an error. :raises ApiConnectionError: Raises if there was a connectivity issue. :rtype: dict """ virtual_host = quote(virtual_host, '') return self.http_client.get(API_VIRTUAL_HOST % virtual_host)
python
def get(self, virtual_host): """Get Virtual Host details. :param str virtual_host: Virtual host name :raises ApiError: Raises if the remote server encountered an error. :raises ApiConnectionError: Raises if there was a connectivity issue. :rtype: dict """ virtual_host = quote(virtual_host, '') return self.http_client.get(API_VIRTUAL_HOST % virtual_host)
Get Virtual Host details. :param str virtual_host: Virtual host name :raises ApiError: Raises if the remote server encountered an error. :raises ApiConnectionError: Raises if there was a connectivity issue. :rtype: dict
https://github.com/eandersson/amqpstorm/blob/38330906c0af19eea482f43c5ce79bab98a1e064/amqpstorm/management/virtual_host.py#L10-L21
eandersson/amqpstorm
amqpstorm/management/virtual_host.py
VirtualHost.create
def create(self, virtual_host): """Create a Virtual Host. :param str virtual_host: Virtual host name :raises ApiError: Raises if the remote server encountered an error. :raises ApiConnectionError: Raises if there was a connectivity issue. :rtype: dict """ virtual_host = quote(virtual_host, '') return self.http_client.put(API_VIRTUAL_HOST % virtual_host)
python
def create(self, virtual_host): """Create a Virtual Host. :param str virtual_host: Virtual host name :raises ApiError: Raises if the remote server encountered an error. :raises ApiConnectionError: Raises if there was a connectivity issue. :rtype: dict """ virtual_host = quote(virtual_host, '') return self.http_client.put(API_VIRTUAL_HOST % virtual_host)
Create a Virtual Host. :param str virtual_host: Virtual host name :raises ApiError: Raises if the remote server encountered an error. :raises ApiConnectionError: Raises if there was a connectivity issue. :rtype: dict
https://github.com/eandersson/amqpstorm/blob/38330906c0af19eea482f43c5ce79bab98a1e064/amqpstorm/management/virtual_host.py#L33-L44
eandersson/amqpstorm
amqpstorm/management/virtual_host.py
VirtualHost.delete
def delete(self, virtual_host): """Delete a Virtual Host. :param str virtual_host: Virtual host name :raises ApiError: Raises if the remote server encountered an error. :raises ApiConnectionError: Raises if there was a connectivity issue. :rtype: dict """ virtual_host = quote(virtual_host, '') return self.http_client.delete(API_VIRTUAL_HOST % virtual_host)
python
def delete(self, virtual_host): """Delete a Virtual Host. :param str virtual_host: Virtual host name :raises ApiError: Raises if the remote server encountered an error. :raises ApiConnectionError: Raises if there was a connectivity issue. :rtype: dict """ virtual_host = quote(virtual_host, '') return self.http_client.delete(API_VIRTUAL_HOST % virtual_host)
Delete a Virtual Host. :param str virtual_host: Virtual host name :raises ApiError: Raises if the remote server encountered an error. :raises ApiConnectionError: Raises if there was a connectivity issue. :rtype: dict
https://github.com/eandersson/amqpstorm/blob/38330906c0af19eea482f43c5ce79bab98a1e064/amqpstorm/management/virtual_host.py#L46-L57
eandersson/amqpstorm
amqpstorm/management/virtual_host.py
VirtualHost.get_permissions
def get_permissions(self, virtual_host): """Get all Virtual hosts permissions. :raises ApiError: Raises if the remote server encountered an error. :raises ApiConnectionError: Raises if there was a connectivity issue. :rtype: dict """ virtual_host = quote(virtual_host, '') return self.http_client.get(API_VIRTUAL_HOSTS_PERMISSION % ( virtual_host ))
python
def get_permissions(self, virtual_host): """Get all Virtual hosts permissions. :raises ApiError: Raises if the remote server encountered an error. :raises ApiConnectionError: Raises if there was a connectivity issue. :rtype: dict """ virtual_host = quote(virtual_host, '') return self.http_client.get(API_VIRTUAL_HOSTS_PERMISSION % ( virtual_host ))
Get all Virtual hosts permissions. :raises ApiError: Raises if the remote server encountered an error. :raises ApiConnectionError: Raises if there was a connectivity issue. :rtype: dict
https://github.com/eandersson/amqpstorm/blob/38330906c0af19eea482f43c5ce79bab98a1e064/amqpstorm/management/virtual_host.py#L59-L71
eandersson/amqpstorm
amqpstorm/base.py
BaseChannel.add_consumer_tag
def add_consumer_tag(self, tag): """Add a Consumer tag. :param str tag: Consumer tag. :return: """ if not is_string(tag): raise AMQPChannelError('consumer tag needs to be a string') if tag not in self._consumer_tags: self._consumer_tags.append(tag)
python
def add_consumer_tag(self, tag): """Add a Consumer tag. :param str tag: Consumer tag. :return: """ if not is_string(tag): raise AMQPChannelError('consumer tag needs to be a string') if tag not in self._consumer_tags: self._consumer_tags.append(tag)
Add a Consumer tag. :param str tag: Consumer tag. :return:
https://github.com/eandersson/amqpstorm/blob/38330906c0af19eea482f43c5ce79bab98a1e064/amqpstorm/base.py#L123-L132
eandersson/amqpstorm
amqpstorm/base.py
BaseChannel.remove_consumer_tag
def remove_consumer_tag(self, tag=None): """Remove a Consumer tag. If no tag is specified, all all tags will be removed. :param str|None tag: Consumer tag. :return: """ if tag is not None: if tag in self._consumer_tags: self._consumer_tags.remove(tag) else: self._consumer_tags = []
python
def remove_consumer_tag(self, tag=None): """Remove a Consumer tag. If no tag is specified, all all tags will be removed. :param str|None tag: Consumer tag. :return: """ if tag is not None: if tag in self._consumer_tags: self._consumer_tags.remove(tag) else: self._consumer_tags = []
Remove a Consumer tag. If no tag is specified, all all tags will be removed. :param str|None tag: Consumer tag. :return:
https://github.com/eandersson/amqpstorm/blob/38330906c0af19eea482f43c5ce79bab98a1e064/amqpstorm/base.py#L134-L146
eandersson/amqpstorm
amqpstorm/base.py
BaseMessage.to_dict
def to_dict(self): """Message to Dictionary. :rtype: dict """ return { 'body': self._body, 'method': self._method, 'properties': self._properties, 'channel': self._channel }
python
def to_dict(self): """Message to Dictionary. :rtype: dict """ return { 'body': self._body, 'method': self._method, 'properties': self._properties, 'channel': self._channel }
Message to Dictionary. :rtype: dict
https://github.com/eandersson/amqpstorm/blob/38330906c0af19eea482f43c5ce79bab98a1e064/amqpstorm/base.py#L171-L181
eandersson/amqpstorm
amqpstorm/base.py
BaseMessage.to_tuple
def to_tuple(self): """Message to Tuple. :rtype: tuple """ return self._body, self._channel, self._method, self._properties
python
def to_tuple(self): """Message to Tuple. :rtype: tuple """ return self._body, self._channel, self._method, self._properties
Message to Tuple. :rtype: tuple
https://github.com/eandersson/amqpstorm/blob/38330906c0af19eea482f43c5ce79bab98a1e064/amqpstorm/base.py#L183-L188
eandersson/amqpstorm
amqpstorm/management/connection.py
Connection.close
def close(self, connection, reason='Closed via management api'): """Close Connection. :param str connection: Connection name :param str reason: Reason for closing connection. :raises ApiError: Raises if the remote server encountered an error. :raises ApiConnectionError: Raises if there was a connectivity issue. :rtype: None """ close_payload = json.dumps({ 'name': connection, 'reason': reason }) connection = quote(connection, '') return self.http_client.delete(API_CONNECTION % connection, payload=close_payload, headers={ 'X-Reason': reason })
python
def close(self, connection, reason='Closed via management api'): """Close Connection. :param str connection: Connection name :param str reason: Reason for closing connection. :raises ApiError: Raises if the remote server encountered an error. :raises ApiConnectionError: Raises if there was a connectivity issue. :rtype: None """ close_payload = json.dumps({ 'name': connection, 'reason': reason }) connection = quote(connection, '') return self.http_client.delete(API_CONNECTION % connection, payload=close_payload, headers={ 'X-Reason': reason })
Close Connection. :param str connection: Connection name :param str reason: Reason for closing connection. :raises ApiError: Raises if the remote server encountered an error. :raises ApiConnectionError: Raises if there was a connectivity issue. :rtype: None
https://github.com/eandersson/amqpstorm/blob/38330906c0af19eea482f43c5ce79bab98a1e064/amqpstorm/management/connection.py#L32-L52
eandersson/amqpstorm
amqpstorm/rpc.py
Rpc.on_frame
def on_frame(self, frame_in): """On RPC Frame. :param specification.Frame frame_in: Amqp frame. :return: """ if frame_in.name not in self._request: return False uuid = self._request[frame_in.name] if self._response[uuid]: self._response[uuid].append(frame_in) else: self._response[uuid] = [frame_in] return True
python
def on_frame(self, frame_in): """On RPC Frame. :param specification.Frame frame_in: Amqp frame. :return: """ if frame_in.name not in self._request: return False uuid = self._request[frame_in.name] if self._response[uuid]: self._response[uuid].append(frame_in) else: self._response[uuid] = [frame_in] return True
On RPC Frame. :param specification.Frame frame_in: Amqp frame. :return:
https://github.com/eandersson/amqpstorm/blob/38330906c0af19eea482f43c5ce79bab98a1e064/amqpstorm/rpc.py#L29-L43
eandersson/amqpstorm
amqpstorm/rpc.py
Rpc.register_request
def register_request(self, valid_responses): """Register a RPC request. :param list valid_responses: List of possible Responses that we should be waiting for. :return: """ uuid = str(uuid4()) self._response[uuid] = [] for action in valid_responses: self._request[action] = uuid return uuid
python
def register_request(self, valid_responses): """Register a RPC request. :param list valid_responses: List of possible Responses that we should be waiting for. :return: """ uuid = str(uuid4()) self._response[uuid] = [] for action in valid_responses: self._request[action] = uuid return uuid
Register a RPC request. :param list valid_responses: List of possible Responses that we should be waiting for. :return:
https://github.com/eandersson/amqpstorm/blob/38330906c0af19eea482f43c5ce79bab98a1e064/amqpstorm/rpc.py#L45-L56
eandersson/amqpstorm
amqpstorm/rpc.py
Rpc.remove_request
def remove_request(self, uuid): """Remove any RPC request(s) using this uuid. :param str uuid: Rpc Identifier. :return: """ for key in list(self._request): if self._request[key] == uuid: del self._request[key]
python
def remove_request(self, uuid): """Remove any RPC request(s) using this uuid. :param str uuid: Rpc Identifier. :return: """ for key in list(self._request): if self._request[key] == uuid: del self._request[key]
Remove any RPC request(s) using this uuid. :param str uuid: Rpc Identifier. :return:
https://github.com/eandersson/amqpstorm/blob/38330906c0af19eea482f43c5ce79bab98a1e064/amqpstorm/rpc.py#L67-L75
eandersson/amqpstorm
amqpstorm/rpc.py
Rpc.get_request
def get_request(self, uuid, raw=False, multiple=False, connection_adapter=None): """Get a RPC request. :param str uuid: Rpc Identifier :param bool raw: If enabled return the frame as is, else return result as a dictionary. :param bool multiple: Are we expecting multiple frames. :param obj connection_adapter: Provide custom connection adapter. :return: """ if uuid not in self._response: return self._wait_for_request( uuid, connection_adapter or self._default_connection_adapter ) frame = self._get_response_frame(uuid) if not multiple: self.remove(uuid) result = None if raw: result = frame elif frame is not None: result = dict(frame) return result
python
def get_request(self, uuid, raw=False, multiple=False, connection_adapter=None): """Get a RPC request. :param str uuid: Rpc Identifier :param bool raw: If enabled return the frame as is, else return result as a dictionary. :param bool multiple: Are we expecting multiple frames. :param obj connection_adapter: Provide custom connection adapter. :return: """ if uuid not in self._response: return self._wait_for_request( uuid, connection_adapter or self._default_connection_adapter ) frame = self._get_response_frame(uuid) if not multiple: self.remove(uuid) result = None if raw: result = frame elif frame is not None: result = dict(frame) return result
Get a RPC request. :param str uuid: Rpc Identifier :param bool raw: If enabled return the frame as is, else return result as a dictionary. :param bool multiple: Are we expecting multiple frames. :param obj connection_adapter: Provide custom connection adapter. :return:
https://github.com/eandersson/amqpstorm/blob/38330906c0af19eea482f43c5ce79bab98a1e064/amqpstorm/rpc.py#L86-L110
eandersson/amqpstorm
amqpstorm/rpc.py
Rpc._get_response_frame
def _get_response_frame(self, uuid): """Get a response frame. :param str uuid: Rpc Identifier :return: """ frame = None frames = self._response.get(uuid, None) if frames: frame = frames.pop(0) return frame
python
def _get_response_frame(self, uuid): """Get a response frame. :param str uuid: Rpc Identifier :return: """ frame = None frames = self._response.get(uuid, None) if frames: frame = frames.pop(0) return frame
Get a response frame. :param str uuid: Rpc Identifier :return:
https://github.com/eandersson/amqpstorm/blob/38330906c0af19eea482f43c5ce79bab98a1e064/amqpstorm/rpc.py#L112-L122
eandersson/amqpstorm
amqpstorm/rpc.py
Rpc._wait_for_request
def _wait_for_request(self, uuid, connection_adapter=None): """Wait for RPC request to arrive. :param str uuid: Rpc Identifier. :param obj connection_adapter: Provide custom connection adapter. :return: """ start_time = time.time() while not self._response[uuid]: connection_adapter.check_for_errors() if time.time() - start_time > self._timeout: self._raise_rpc_timeout_error(uuid) time.sleep(IDLE_WAIT)
python
def _wait_for_request(self, uuid, connection_adapter=None): """Wait for RPC request to arrive. :param str uuid: Rpc Identifier. :param obj connection_adapter: Provide custom connection adapter. :return: """ start_time = time.time() while not self._response[uuid]: connection_adapter.check_for_errors() if time.time() - start_time > self._timeout: self._raise_rpc_timeout_error(uuid) time.sleep(IDLE_WAIT)
Wait for RPC request to arrive. :param str uuid: Rpc Identifier. :param obj connection_adapter: Provide custom connection adapter. :return:
https://github.com/eandersson/amqpstorm/blob/38330906c0af19eea482f43c5ce79bab98a1e064/amqpstorm/rpc.py#L124-L136
eandersson/amqpstorm
amqpstorm/rpc.py
Rpc._raise_rpc_timeout_error
def _raise_rpc_timeout_error(self, uuid): """Gather information and raise an Rpc exception. :param str uuid: Rpc Identifier. :return: """ requests = [] for key, value in self._request.items(): if value == uuid: requests.append(key) self.remove(uuid) message = ( 'rpc requests %s (%s) took too long' % ( uuid, ', '.join(requests) ) ) raise AMQPChannelError(message)
python
def _raise_rpc_timeout_error(self, uuid): """Gather information and raise an Rpc exception. :param str uuid: Rpc Identifier. :return: """ requests = [] for key, value in self._request.items(): if value == uuid: requests.append(key) self.remove(uuid) message = ( 'rpc requests %s (%s) took too long' % ( uuid, ', '.join(requests) ) ) raise AMQPChannelError(message)
Gather information and raise an Rpc exception. :param str uuid: Rpc Identifier. :return:
https://github.com/eandersson/amqpstorm/blob/38330906c0af19eea482f43c5ce79bab98a1e064/amqpstorm/rpc.py#L138-L156
eandersson/amqpstorm
amqpstorm/compatibility.py
get_default_ssl_version
def get_default_ssl_version(): """Get the highest support TLS version, if none is available, return None. :rtype: bool|None """ if hasattr(ssl, 'PROTOCOL_TLSv1_2'): return ssl.PROTOCOL_TLSv1_2 elif hasattr(ssl, 'PROTOCOL_TLSv1_1'): return ssl.PROTOCOL_TLSv1_1 elif hasattr(ssl, 'PROTOCOL_TLSv1'): return ssl.PROTOCOL_TLSv1 return None
python
def get_default_ssl_version(): """Get the highest support TLS version, if none is available, return None. :rtype: bool|None """ if hasattr(ssl, 'PROTOCOL_TLSv1_2'): return ssl.PROTOCOL_TLSv1_2 elif hasattr(ssl, 'PROTOCOL_TLSv1_1'): return ssl.PROTOCOL_TLSv1_1 elif hasattr(ssl, 'PROTOCOL_TLSv1'): return ssl.PROTOCOL_TLSv1 return None
Get the highest support TLS version, if none is available, return None. :rtype: bool|None
https://github.com/eandersson/amqpstorm/blob/38330906c0af19eea482f43c5ce79bab98a1e064/amqpstorm/compatibility.py#L44-L55
eandersson/amqpstorm
amqpstorm/compatibility.py
is_string
def is_string(obj): """Is this a string. :param object obj: :rtype: bool """ if PYTHON3: str_type = (bytes, str) else: str_type = (bytes, str, unicode) return isinstance(obj, str_type)
python
def is_string(obj): """Is this a string. :param object obj: :rtype: bool """ if PYTHON3: str_type = (bytes, str) else: str_type = (bytes, str, unicode) return isinstance(obj, str_type)
Is this a string. :param object obj: :rtype: bool
https://github.com/eandersson/amqpstorm/blob/38330906c0af19eea482f43c5ce79bab98a1e064/amqpstorm/compatibility.py#L74-L84
eandersson/amqpstorm
amqpstorm/compatibility.py
is_integer
def is_integer(obj): """Is this an integer. :param object obj: :return: """ if PYTHON3: return isinstance(obj, int) return isinstance(obj, (int, long))
python
def is_integer(obj): """Is this an integer. :param object obj: :return: """ if PYTHON3: return isinstance(obj, int) return isinstance(obj, (int, long))
Is this an integer. :param object obj: :return:
https://github.com/eandersson/amqpstorm/blob/38330906c0af19eea482f43c5ce79bab98a1e064/amqpstorm/compatibility.py#L87-L95
eandersson/amqpstorm
amqpstorm/compatibility.py
try_utf8_decode
def try_utf8_decode(value): """Try to decode an object. :param value: :return: """ if not value or not is_string(value): return value elif PYTHON3 and not isinstance(value, bytes): return value elif not PYTHON3 and not isinstance(value, unicode): return value try: return value.decode('utf-8') except UnicodeDecodeError: pass return value
python
def try_utf8_decode(value): """Try to decode an object. :param value: :return: """ if not value or not is_string(value): return value elif PYTHON3 and not isinstance(value, bytes): return value elif not PYTHON3 and not isinstance(value, unicode): return value try: return value.decode('utf-8') except UnicodeDecodeError: pass return value
Try to decode an object. :param value: :return:
https://github.com/eandersson/amqpstorm/blob/38330906c0af19eea482f43c5ce79bab98a1e064/amqpstorm/compatibility.py#L111-L129
eandersson/amqpstorm
amqpstorm/compatibility.py
patch_uri
def patch_uri(uri): """If a custom uri schema is used with python 2.6 (e.g. amqps), it will ignore some of the parsing logic. As a work-around for this we change the amqp/amqps schema internally to use http/https. :param str uri: AMQP Connection string :rtype: str """ index = uri.find(':') if uri[:index] == 'amqps': uri = uri.replace('amqps', 'https', 1) elif uri[:index] == 'amqp': uri = uri.replace('amqp', 'http', 1) return uri
python
def patch_uri(uri): """If a custom uri schema is used with python 2.6 (e.g. amqps), it will ignore some of the parsing logic. As a work-around for this we change the amqp/amqps schema internally to use http/https. :param str uri: AMQP Connection string :rtype: str """ index = uri.find(':') if uri[:index] == 'amqps': uri = uri.replace('amqps', 'https', 1) elif uri[:index] == 'amqp': uri = uri.replace('amqp', 'http', 1) return uri
If a custom uri schema is used with python 2.6 (e.g. amqps), it will ignore some of the parsing logic. As a work-around for this we change the amqp/amqps schema internally to use http/https. :param str uri: AMQP Connection string :rtype: str
https://github.com/eandersson/amqpstorm/blob/38330906c0af19eea482f43c5ce79bab98a1e064/amqpstorm/compatibility.py#L132-L147
eandersson/amqpstorm
amqpstorm/uri_connection.py
UriConnection._parse_uri_options
def _parse_uri_options(self, parsed_uri, use_ssl=False, ssl_options=None): """Parse the uri options. :param parsed_uri: :param bool use_ssl: :return: """ ssl_options = ssl_options or {} kwargs = urlparse.parse_qs(parsed_uri.query) vhost = urlparse.unquote(parsed_uri.path[1:]) or DEFAULT_VIRTUAL_HOST options = { 'ssl': use_ssl, 'virtual_host': vhost, 'heartbeat': int(kwargs.pop('heartbeat', [DEFAULT_HEARTBEAT_INTERVAL])[0]), 'timeout': int(kwargs.pop('timeout', [DEFAULT_SOCKET_TIMEOUT])[0]) } if use_ssl: if not compatibility.SSL_SUPPORTED: raise AMQPConnectionError( 'Python not compiled with support ' 'for TLSv1 or higher' ) ssl_options.update(self._parse_ssl_options(kwargs)) options['ssl_options'] = ssl_options return options
python
def _parse_uri_options(self, parsed_uri, use_ssl=False, ssl_options=None): """Parse the uri options. :param parsed_uri: :param bool use_ssl: :return: """ ssl_options = ssl_options or {} kwargs = urlparse.parse_qs(parsed_uri.query) vhost = urlparse.unquote(parsed_uri.path[1:]) or DEFAULT_VIRTUAL_HOST options = { 'ssl': use_ssl, 'virtual_host': vhost, 'heartbeat': int(kwargs.pop('heartbeat', [DEFAULT_HEARTBEAT_INTERVAL])[0]), 'timeout': int(kwargs.pop('timeout', [DEFAULT_SOCKET_TIMEOUT])[0]) } if use_ssl: if not compatibility.SSL_SUPPORTED: raise AMQPConnectionError( 'Python not compiled with support ' 'for TLSv1 or higher' ) ssl_options.update(self._parse_ssl_options(kwargs)) options['ssl_options'] = ssl_options return options
Parse the uri options. :param parsed_uri: :param bool use_ssl: :return:
https://github.com/eandersson/amqpstorm/blob/38330906c0af19eea482f43c5ce79bab98a1e064/amqpstorm/uri_connection.py#L51-L77
eandersson/amqpstorm
amqpstorm/uri_connection.py
UriConnection._parse_ssl_options
def _parse_ssl_options(self, ssl_kwargs): """Parse TLS Options. :param ssl_kwargs: :rtype: dict """ ssl_options = {} for key in ssl_kwargs: if key not in compatibility.SSL_OPTIONS: LOGGER.warning('invalid option: %s', key) continue if 'ssl_version' in key: value = self._get_ssl_version(ssl_kwargs[key][0]) elif 'cert_reqs' in key: value = self._get_ssl_validation(ssl_kwargs[key][0]) else: value = ssl_kwargs[key][0] ssl_options[key] = value return ssl_options
python
def _parse_ssl_options(self, ssl_kwargs): """Parse TLS Options. :param ssl_kwargs: :rtype: dict """ ssl_options = {} for key in ssl_kwargs: if key not in compatibility.SSL_OPTIONS: LOGGER.warning('invalid option: %s', key) continue if 'ssl_version' in key: value = self._get_ssl_version(ssl_kwargs[key][0]) elif 'cert_reqs' in key: value = self._get_ssl_validation(ssl_kwargs[key][0]) else: value = ssl_kwargs[key][0] ssl_options[key] = value return ssl_options
Parse TLS Options. :param ssl_kwargs: :rtype: dict
https://github.com/eandersson/amqpstorm/blob/38330906c0af19eea482f43c5ce79bab98a1e064/amqpstorm/uri_connection.py#L79-L97
eandersson/amqpstorm
amqpstorm/uri_connection.py
UriConnection._get_ssl_version
def _get_ssl_version(self, value): """Get the TLS Version. :param str value: :return: TLS Version """ return self._get_ssl_attribute(value, compatibility.SSL_VERSIONS, ssl.PROTOCOL_TLSv1, 'ssl_options: ssl_version \'%s\' not ' 'found falling back to PROTOCOL_TLSv1.')
python
def _get_ssl_version(self, value): """Get the TLS Version. :param str value: :return: TLS Version """ return self._get_ssl_attribute(value, compatibility.SSL_VERSIONS, ssl.PROTOCOL_TLSv1, 'ssl_options: ssl_version \'%s\' not ' 'found falling back to PROTOCOL_TLSv1.')
Get the TLS Version. :param str value: :return: TLS Version
https://github.com/eandersson/amqpstorm/blob/38330906c0af19eea482f43c5ce79bab98a1e064/amqpstorm/uri_connection.py#L99-L108
eandersson/amqpstorm
amqpstorm/uri_connection.py
UriConnection._get_ssl_validation
def _get_ssl_validation(self, value): """Get the TLS Validation option. :param str value: :return: TLS Certificate Options """ return self._get_ssl_attribute(value, compatibility.SSL_CERT_MAP, ssl.CERT_NONE, 'ssl_options: cert_reqs \'%s\' not ' 'found falling back to CERT_NONE.')
python
def _get_ssl_validation(self, value): """Get the TLS Validation option. :param str value: :return: TLS Certificate Options """ return self._get_ssl_attribute(value, compatibility.SSL_CERT_MAP, ssl.CERT_NONE, 'ssl_options: cert_reqs \'%s\' not ' 'found falling back to CERT_NONE.')
Get the TLS Validation option. :param str value: :return: TLS Certificate Options
https://github.com/eandersson/amqpstorm/blob/38330906c0af19eea482f43c5ce79bab98a1e064/amqpstorm/uri_connection.py#L110-L119
eandersson/amqpstorm
amqpstorm/uri_connection.py
UriConnection._get_ssl_attribute
def _get_ssl_attribute(value, mapping, default_value, warning_message): """Get the TLS attribute based on the compatibility mapping. If no valid attribute can be found, fall-back on default and display a warning. :param str value: :param dict mapping: Dictionary based mapping :param default_value: Default fall-back value :param str warning_message: Warning message :return: """ for key in mapping: if not key.endswith(value.lower()): continue return mapping[key] LOGGER.warning(warning_message, value) return default_value
python
def _get_ssl_attribute(value, mapping, default_value, warning_message): """Get the TLS attribute based on the compatibility mapping. If no valid attribute can be found, fall-back on default and display a warning. :param str value: :param dict mapping: Dictionary based mapping :param default_value: Default fall-back value :param str warning_message: Warning message :return: """ for key in mapping: if not key.endswith(value.lower()): continue return mapping[key] LOGGER.warning(warning_message, value) return default_value
Get the TLS attribute based on the compatibility mapping. If no valid attribute can be found, fall-back on default and display a warning. :param str value: :param dict mapping: Dictionary based mapping :param default_value: Default fall-back value :param str warning_message: Warning message :return:
https://github.com/eandersson/amqpstorm/blob/38330906c0af19eea482f43c5ce79bab98a1e064/amqpstorm/uri_connection.py#L122-L139
eandersson/amqpstorm
amqpstorm/management/api.py
ManagementApi.top
def top(self): """Top Processes. :raises ApiError: Raises if the remote server encountered an error. :raises ApiConnectionError: Raises if there was a connectivity issue. :rtype: list """ nodes = [] for node in self.nodes(): nodes.append(self.http_client.get(API_TOP % node['name'])) return nodes
python
def top(self): """Top Processes. :raises ApiError: Raises if the remote server encountered an error. :raises ApiConnectionError: Raises if there was a connectivity issue. :rtype: list """ nodes = [] for node in self.nodes(): nodes.append(self.http_client.get(API_TOP % node['name'])) return nodes
Top Processes. :raises ApiError: Raises if the remote server encountered an error. :raises ApiConnectionError: Raises if there was a connectivity issue. :rtype: list
https://github.com/eandersson/amqpstorm/blob/38330906c0af19eea482f43c5ce79bab98a1e064/amqpstorm/management/api.py#L133-L144
eandersson/amqpstorm
amqpstorm/basic.py
Basic.qos
def qos(self, prefetch_count=0, prefetch_size=0, global_=False): """Specify quality of service. :param int prefetch_count: Prefetch window in messages :param int/long prefetch_size: Prefetch window in octets :param bool global_: Apply to entire connection :raises AMQPInvalidArgument: Invalid Parameters :raises AMQPChannelError: Raises if the channel encountered an error. :raises AMQPConnectionError: Raises if the connection encountered an error. :rtype: dict """ if not compatibility.is_integer(prefetch_count): raise AMQPInvalidArgument('prefetch_count should be an integer') elif not compatibility.is_integer(prefetch_size): raise AMQPInvalidArgument('prefetch_size should be an integer') elif not isinstance(global_, bool): raise AMQPInvalidArgument('global_ should be a boolean') qos_frame = specification.Basic.Qos(prefetch_count=prefetch_count, prefetch_size=prefetch_size, global_=global_) return self._channel.rpc_request(qos_frame)
python
def qos(self, prefetch_count=0, prefetch_size=0, global_=False): """Specify quality of service. :param int prefetch_count: Prefetch window in messages :param int/long prefetch_size: Prefetch window in octets :param bool global_: Apply to entire connection :raises AMQPInvalidArgument: Invalid Parameters :raises AMQPChannelError: Raises if the channel encountered an error. :raises AMQPConnectionError: Raises if the connection encountered an error. :rtype: dict """ if not compatibility.is_integer(prefetch_count): raise AMQPInvalidArgument('prefetch_count should be an integer') elif not compatibility.is_integer(prefetch_size): raise AMQPInvalidArgument('prefetch_size should be an integer') elif not isinstance(global_, bool): raise AMQPInvalidArgument('global_ should be a boolean') qos_frame = specification.Basic.Qos(prefetch_count=prefetch_count, prefetch_size=prefetch_size, global_=global_) return self._channel.rpc_request(qos_frame)
Specify quality of service. :param int prefetch_count: Prefetch window in messages :param int/long prefetch_size: Prefetch window in octets :param bool global_: Apply to entire connection :raises AMQPInvalidArgument: Invalid Parameters :raises AMQPChannelError: Raises if the channel encountered an error. :raises AMQPConnectionError: Raises if the connection encountered an error. :rtype: dict
https://github.com/eandersson/amqpstorm/blob/38330906c0af19eea482f43c5ce79bab98a1e064/amqpstorm/basic.py#L28-L51
eandersson/amqpstorm
amqpstorm/basic.py
Basic.get
def get(self, queue='', no_ack=False, to_dict=False, auto_decode=True): """Fetch a single message. :param str queue: Queue name :param bool no_ack: No acknowledgement needed :param bool to_dict: Should incoming messages be converted to a dictionary before delivery. :param bool auto_decode: Auto-decode strings when possible. :raises AMQPInvalidArgument: Invalid Parameters :raises AMQPChannelError: Raises if the channel encountered an error. :raises AMQPConnectionError: Raises if the connection encountered an error. :returns: Returns a single message, as long as there is a message in the queue. If no message is available, returns None. :rtype: dict|Message|None """ if not compatibility.is_string(queue): raise AMQPInvalidArgument('queue should be a string') elif not isinstance(no_ack, bool): raise AMQPInvalidArgument('no_ack should be a boolean') elif self._channel.consumer_tags: raise AMQPChannelError("Cannot call 'get' when channel is " "set to consume") get_frame = specification.Basic.Get(queue=queue, no_ack=no_ack) with self._channel.lock and self._channel.rpc.lock: message = self._get_message(get_frame, auto_decode=auto_decode) if message and to_dict: return message.to_dict() return message
python
def get(self, queue='', no_ack=False, to_dict=False, auto_decode=True): """Fetch a single message. :param str queue: Queue name :param bool no_ack: No acknowledgement needed :param bool to_dict: Should incoming messages be converted to a dictionary before delivery. :param bool auto_decode: Auto-decode strings when possible. :raises AMQPInvalidArgument: Invalid Parameters :raises AMQPChannelError: Raises if the channel encountered an error. :raises AMQPConnectionError: Raises if the connection encountered an error. :returns: Returns a single message, as long as there is a message in the queue. If no message is available, returns None. :rtype: dict|Message|None """ if not compatibility.is_string(queue): raise AMQPInvalidArgument('queue should be a string') elif not isinstance(no_ack, bool): raise AMQPInvalidArgument('no_ack should be a boolean') elif self._channel.consumer_tags: raise AMQPChannelError("Cannot call 'get' when channel is " "set to consume") get_frame = specification.Basic.Get(queue=queue, no_ack=no_ack) with self._channel.lock and self._channel.rpc.lock: message = self._get_message(get_frame, auto_decode=auto_decode) if message and to_dict: return message.to_dict() return message
Fetch a single message. :param str queue: Queue name :param bool no_ack: No acknowledgement needed :param bool to_dict: Should incoming messages be converted to a dictionary before delivery. :param bool auto_decode: Auto-decode strings when possible. :raises AMQPInvalidArgument: Invalid Parameters :raises AMQPChannelError: Raises if the channel encountered an error. :raises AMQPConnectionError: Raises if the connection encountered an error. :returns: Returns a single message, as long as there is a message in the queue. If no message is available, returns None. :rtype: dict|Message|None
https://github.com/eandersson/amqpstorm/blob/38330906c0af19eea482f43c5ce79bab98a1e064/amqpstorm/basic.py#L53-L85
eandersson/amqpstorm
amqpstorm/basic.py
Basic.recover
def recover(self, requeue=False): """Redeliver unacknowledged messages. :param bool requeue: Re-queue the messages :raises AMQPInvalidArgument: Invalid Parameters :raises AMQPChannelError: Raises if the channel encountered an error. :raises AMQPConnectionError: Raises if the connection encountered an error. :rtype: dict """ if not isinstance(requeue, bool): raise AMQPInvalidArgument('requeue should be a boolean') recover_frame = specification.Basic.Recover(requeue=requeue) return self._channel.rpc_request(recover_frame)
python
def recover(self, requeue=False): """Redeliver unacknowledged messages. :param bool requeue: Re-queue the messages :raises AMQPInvalidArgument: Invalid Parameters :raises AMQPChannelError: Raises if the channel encountered an error. :raises AMQPConnectionError: Raises if the connection encountered an error. :rtype: dict """ if not isinstance(requeue, bool): raise AMQPInvalidArgument('requeue should be a boolean') recover_frame = specification.Basic.Recover(requeue=requeue) return self._channel.rpc_request(recover_frame)
Redeliver unacknowledged messages. :param bool requeue: Re-queue the messages :raises AMQPInvalidArgument: Invalid Parameters :raises AMQPChannelError: Raises if the channel encountered an error. :raises AMQPConnectionError: Raises if the connection encountered an error. :rtype: dict
https://github.com/eandersson/amqpstorm/blob/38330906c0af19eea482f43c5ce79bab98a1e064/amqpstorm/basic.py#L87-L102
eandersson/amqpstorm
amqpstorm/basic.py
Basic.consume
def consume(self, callback=None, queue='', consumer_tag='', exclusive=False, no_ack=False, no_local=False, arguments=None): """Start a queue consumer. :param function callback: Message callback :param str queue: Queue name :param str consumer_tag: Consumer tag :param bool no_local: Do not deliver own messages :param bool no_ack: No acknowledgement needed :param bool exclusive: Request exclusive access :param dict arguments: Consume key/value arguments :raises AMQPInvalidArgument: Invalid Parameters :raises AMQPChannelError: Raises if the channel encountered an error. :raises AMQPConnectionError: Raises if the connection encountered an error. :returns: Consumer tag :rtype: str """ if not compatibility.is_string(queue): raise AMQPInvalidArgument('queue should be a string') elif not compatibility.is_string(consumer_tag): raise AMQPInvalidArgument('consumer_tag should be a string') elif not isinstance(exclusive, bool): raise AMQPInvalidArgument('exclusive should be a boolean') elif not isinstance(no_ack, bool): raise AMQPInvalidArgument('no_ack should be a boolean') elif not isinstance(no_local, bool): raise AMQPInvalidArgument('no_local should be a boolean') elif arguments is not None and not isinstance(arguments, dict): raise AMQPInvalidArgument('arguments should be a dict or None') consume_rpc_result = self._consume_rpc_request(arguments, consumer_tag, exclusive, no_ack, no_local, queue) tag = self._consume_add_and_get_tag(consume_rpc_result) self._channel._consumer_callbacks[tag] = callback return tag
python
def consume(self, callback=None, queue='', consumer_tag='', exclusive=False, no_ack=False, no_local=False, arguments=None): """Start a queue consumer. :param function callback: Message callback :param str queue: Queue name :param str consumer_tag: Consumer tag :param bool no_local: Do not deliver own messages :param bool no_ack: No acknowledgement needed :param bool exclusive: Request exclusive access :param dict arguments: Consume key/value arguments :raises AMQPInvalidArgument: Invalid Parameters :raises AMQPChannelError: Raises if the channel encountered an error. :raises AMQPConnectionError: Raises if the connection encountered an error. :returns: Consumer tag :rtype: str """ if not compatibility.is_string(queue): raise AMQPInvalidArgument('queue should be a string') elif not compatibility.is_string(consumer_tag): raise AMQPInvalidArgument('consumer_tag should be a string') elif not isinstance(exclusive, bool): raise AMQPInvalidArgument('exclusive should be a boolean') elif not isinstance(no_ack, bool): raise AMQPInvalidArgument('no_ack should be a boolean') elif not isinstance(no_local, bool): raise AMQPInvalidArgument('no_local should be a boolean') elif arguments is not None and not isinstance(arguments, dict): raise AMQPInvalidArgument('arguments should be a dict or None') consume_rpc_result = self._consume_rpc_request(arguments, consumer_tag, exclusive, no_ack, no_local, queue) tag = self._consume_add_and_get_tag(consume_rpc_result) self._channel._consumer_callbacks[tag] = callback return tag
Start a queue consumer. :param function callback: Message callback :param str queue: Queue name :param str consumer_tag: Consumer tag :param bool no_local: Do not deliver own messages :param bool no_ack: No acknowledgement needed :param bool exclusive: Request exclusive access :param dict arguments: Consume key/value arguments :raises AMQPInvalidArgument: Invalid Parameters :raises AMQPChannelError: Raises if the channel encountered an error. :raises AMQPConnectionError: Raises if the connection encountered an error. :returns: Consumer tag :rtype: str
https://github.com/eandersson/amqpstorm/blob/38330906c0af19eea482f43c5ce79bab98a1e064/amqpstorm/basic.py#L104-L141
eandersson/amqpstorm
amqpstorm/basic.py
Basic.cancel
def cancel(self, consumer_tag=''): """Cancel a queue consumer. :param str consumer_tag: Consumer tag :raises AMQPInvalidArgument: Invalid Parameters :raises AMQPChannelError: Raises if the channel encountered an error. :raises AMQPConnectionError: Raises if the connection encountered an error. :rtype: dict """ if not compatibility.is_string(consumer_tag): raise AMQPInvalidArgument('consumer_tag should be a string') cancel_frame = specification.Basic.Cancel(consumer_tag=consumer_tag) result = self._channel.rpc_request(cancel_frame) self._channel.remove_consumer_tag(consumer_tag) return result
python
def cancel(self, consumer_tag=''): """Cancel a queue consumer. :param str consumer_tag: Consumer tag :raises AMQPInvalidArgument: Invalid Parameters :raises AMQPChannelError: Raises if the channel encountered an error. :raises AMQPConnectionError: Raises if the connection encountered an error. :rtype: dict """ if not compatibility.is_string(consumer_tag): raise AMQPInvalidArgument('consumer_tag should be a string') cancel_frame = specification.Basic.Cancel(consumer_tag=consumer_tag) result = self._channel.rpc_request(cancel_frame) self._channel.remove_consumer_tag(consumer_tag) return result
Cancel a queue consumer. :param str consumer_tag: Consumer tag :raises AMQPInvalidArgument: Invalid Parameters :raises AMQPChannelError: Raises if the channel encountered an error. :raises AMQPConnectionError: Raises if the connection encountered an error. :rtype: dict
https://github.com/eandersson/amqpstorm/blob/38330906c0af19eea482f43c5ce79bab98a1e064/amqpstorm/basic.py#L143-L160
eandersson/amqpstorm
amqpstorm/basic.py
Basic.publish
def publish(self, body, routing_key, exchange='', properties=None, mandatory=False, immediate=False): """Publish a Message. :param bytes|str|unicode body: Message payload :param str routing_key: Message routing key :param str exchange: The exchange to publish the message to :param dict properties: Message properties :param bool mandatory: Requires the message is published :param bool immediate: Request immediate delivery :raises AMQPInvalidArgument: Invalid Parameters :raises AMQPChannelError: Raises if the channel encountered an error. :raises AMQPConnectionError: Raises if the connection encountered an error. :rtype: bool|None """ self._validate_publish_parameters(body, exchange, immediate, mandatory, properties, routing_key) properties = properties or {} body = self._handle_utf8_payload(body, properties) properties = specification.Basic.Properties(**properties) method_frame = specification.Basic.Publish(exchange=exchange, routing_key=routing_key, mandatory=mandatory, immediate=immediate) header_frame = pamqp_header.ContentHeader(body_size=len(body), properties=properties) frames_out = [method_frame, header_frame] for body_frame in self._create_content_body(body): frames_out.append(body_frame) if self._channel.confirming_deliveries: with self._channel.rpc.lock: return self._publish_confirm(frames_out) self._channel.write_frames(frames_out)
python
def publish(self, body, routing_key, exchange='', properties=None, mandatory=False, immediate=False): """Publish a Message. :param bytes|str|unicode body: Message payload :param str routing_key: Message routing key :param str exchange: The exchange to publish the message to :param dict properties: Message properties :param bool mandatory: Requires the message is published :param bool immediate: Request immediate delivery :raises AMQPInvalidArgument: Invalid Parameters :raises AMQPChannelError: Raises if the channel encountered an error. :raises AMQPConnectionError: Raises if the connection encountered an error. :rtype: bool|None """ self._validate_publish_parameters(body, exchange, immediate, mandatory, properties, routing_key) properties = properties or {} body = self._handle_utf8_payload(body, properties) properties = specification.Basic.Properties(**properties) method_frame = specification.Basic.Publish(exchange=exchange, routing_key=routing_key, mandatory=mandatory, immediate=immediate) header_frame = pamqp_header.ContentHeader(body_size=len(body), properties=properties) frames_out = [method_frame, header_frame] for body_frame in self._create_content_body(body): frames_out.append(body_frame) if self._channel.confirming_deliveries: with self._channel.rpc.lock: return self._publish_confirm(frames_out) self._channel.write_frames(frames_out)
Publish a Message. :param bytes|str|unicode body: Message payload :param str routing_key: Message routing key :param str exchange: The exchange to publish the message to :param dict properties: Message properties :param bool mandatory: Requires the message is published :param bool immediate: Request immediate delivery :raises AMQPInvalidArgument: Invalid Parameters :raises AMQPChannelError: Raises if the channel encountered an error. :raises AMQPConnectionError: Raises if the connection encountered an error. :rtype: bool|None
https://github.com/eandersson/amqpstorm/blob/38330906c0af19eea482f43c5ce79bab98a1e064/amqpstorm/basic.py#L162-L199