desc
stringlengths
3
26.7k
decl
stringlengths
11
7.89k
bodies
stringlengths
8
553k
'If an on_signal_callback has been defined, call it returning the string \'SIGINT\'.'
def _handle_sigint(self, signal_watcher, libev_events):
LOGGER.debug('SIGINT') self._on_signal_callback('SIGINT')
'If an on_signal_callback has been defined, call it returning the string \'SIGTERM\'.'
def _handle_sigterm(self, signal_watcher, libev_events):
LOGGER.debug('SIGTERM') self._on_signal_callback('SIGTERM')
'Handle IO events by efficiently translating to BaseConnection events and calling super.'
def _handle_events(self, io_watcher, libev_events, **kwargs):
super(LibevConnection, self)._handle_events(io_watcher.fd, self._LIBEV_TO_PIKA_ARRAY[libev_events], **kwargs)
'Reset the IO watcher; retry as necessary'
def _reset_io_watcher(self):
self._io_watcher.stop() retries = 0 while True: try: self._io_watcher.set(self._io_watcher.fd, self._PIKA_TO_LIBEV_ARRAY[self.event_state]) break except Exception: if (retries > 5): raise self._io_watcher.stop() retr...
'Manage the bitmask for reading/writing/error which is used by the io/event handler to specify when there is an event such as a read or write.'
def _manage_event_state(self):
if self.outbound_buffer: if (not (self.event_state & self.WRITE)): self.event_state |= self.WRITE self._reset_io_watcher() elif (self.event_state & self.WRITE): self.event_state = self.base_events self._reset_io_watcher()
'Manage timer callbacks indirectly.'
def _timer_callback(self, timer, libev_events):
if (timer in self._active_timers): (callback_method, callback_timeout, kwargs) = self._active_timers[timer] self.remove_timeout(timer) if callback_timeout: callback_method(timeout=timer, **kwargs) else: callback_method(**kwargs) else: LOGGER.warnin...
'Get a timer from the pool or allocate a new one.'
def _get_timer(self, deadline):
if self._stopped_timers: timer = self._stopped_timers.pop() timer.set(deadline, 0.0) else: timer = self.ioloop.timer(deadline, 0.0, self._timer_callback) return timer
'Add the callback_method indirectly to the IOLoop timer to fire after deadline seconds. Returns the timer handle. :param int deadline: The number of seconds to wait to call callback :param method callback_method: The callback method :param callback_timeout: Whether timeout kwarg is passed on callback :type callback_tim...
def add_timeout(self, deadline, callback_method, callback_timeout=False, **callback_kwargs):
LOGGER.debug('deadline: %s', deadline) timer = self._get_timer(deadline) self._active_timers[timer] = (callback_method, callback_timeout, callback_kwargs) timer.start() return timer
'Remove the timer from the IOLoop using the handle returned from add_timeout. param: timer instance handle'
def remove_timeout(self, timer):
LOGGER.debug('stop') try: self._active_timers.pop(timer) except KeyError: LOGGER.warning('Attempted to remove inactive timer %s', timer) else: timer.stop() self._stopped_timers.append(timer)
'Call super and then set the socket to nonblocking.'
def _create_and_connect_to_socket(self, sock_addr_tuple):
result = super(LibevConnection, self)._create_and_connect_to_socket(sock_addr_tuple) if result: self.socket.setblocking(0) return result
':param callable value_class: only needed if the CallbackResult instance will be used with `set_value_once` and `append_element`. *args and **kwargs of the value setter methods will be passed to this class.'
def __init__(self, value_class=None):
self._value_class = value_class self._ready = None self._values = None self.reset()
'Reset value, but not _value_class'
def reset(self):
self._ready = False self._values = None
'Called by python runtime to implement truth value testing and the built-in operation bool(); NOTE: python 3.x'
def __bool__(self):
return self.is_ready()
'Entry into context manager that automatically resets the object on exit; this usage pattern helps garbage-collection by eliminating potential circular references.'
def __enter__(self):
return self
'Reset value'
def __exit__(self, *args, **kwargs):
self.reset()
':returns: True if the object is in a signaled state'
def is_ready(self):
return self._ready
'True if the object is in a signaled state'
@property def ready(self):
return self._ready
'Set as ready :raises AssertionError: if result was already signalled'
def signal_once(self, *_args, **_kwargs):
assert (not self._ready), '_CallbackResult was already set' self._ready = True
'Set as ready with value; the value may be retrived via the `value` property getter :raises AssertionError: if result was already set'
def set_value_once(self, *args, **kwargs):
self.signal_once() try: self._values = (self._value_class(*args, **kwargs),) except Exception: LOGGER.error('set_value_once failed: value_class=%r; args=%r; kwargs=%r', self._value_class, args, kwargs) raise
'Append an element to values'
def append_element(self, *args, **kwargs):
assert ((not self._ready) or isinstance(self._values, list)), ('_CallbackResult state is incompatible with append_element: ready=%r; values=%r' % (self._ready, self._values)) try: value = self._value_class(*args, **kwargs) except Exception: LOGGER.error('append_element ...
':returns: a reference to the value that was set via `set_value_once` :raises AssertionError: if result was not set or value is incompatible with `set_value_once`'
@property def value(self):
assert self._ready, '_CallbackResult was not set' assert (isinstance(self._values, tuple) and (len(self._values) == 1)), ('_CallbackResult value is incompatible with set_value_once: %r' % (self._values,)) return self._values[0]
':returns: a reference to the list containing one or more elements that were added via `append_element` :raises AssertionError: if result was not set or value is incompatible with `append_element`'
@property def elements(self):
assert self._ready, '_CallbackResult was not set' assert (isinstance(self._values, list) and (len(self._values) > 0)), ('_CallbackResult value is incompatible with append_element: %r' % (self._values,)) return self._values
':param float duration: non-negative timer duration in seconds :param SelectConnection connection:'
def __init__(self, duration, connection):
assert hasattr(connection, 'add_timeout'), connection self._duration = duration self._connection = connection self._callback_result = _CallbackResult() self._timer_id = None
'Register a timer'
def __enter__(self):
self._timer_id = self._connection.add_timeout(self._duration, self._callback_result.signal_once) return self
'Unregister timer if it hasn\'t fired yet'
def __exit__(self, *_args, **_kwargs):
if (not self._callback_result): self._connection.remove_timeout(self._timer_id)
':returns: True if timer has fired, False otherwise'
def is_ready(self):
return self._callback_result.is_ready()
':param callback: see callback_method in `BlockingConnection.add_timeout`'
def __init__(self, callback):
self._callback = callback self.timer_id = None
'Dispatch the user\'s callback method'
def dispatch(self):
self._callback()
':param callback: see callback_method parameter in `BlockingConnection.add_on_connection_blocked_callback` and `BlockingConnection.add_on_connection_unblocked_callback` :param pika.frame.Method method_frame: with method_frame.method of type `pika.spec.Connection.Blocked` or `pika.spec.Connection.Unblocked`'
def __init__(self, callback, method_frame):
self._callback = callback self._method_frame = method_frame
'Dispatch the user\'s callback method'
def dispatch(self):
self._callback(self._method_frame)
'Create a new instance of the Connection object. :param pika.connection.Parameters parameters: Connection parameters :param _impl_class: for tests/debugging only; implementation class; None=default :raises RuntimeError:'
def __init__(self, parameters=None, _impl_class=None):
self._event_dispatch_suspend_depth = 0 self._ready_events = deque() self._channels_pending_dispatch = set() self._opened_result = _CallbackResult(self._OnOpenedArgs) self._open_error_result = _CallbackResult(self._OnOpenErrorArgs) self._closed_result = _CallbackResult(self._OnClosedArgs) sel...
'Clean up members that might inhibit garbage collection'
def _cleanup(self):
self._impl.ioloop.deactivate_poller() self._ready_events.clear() self._opened_result.reset() self._open_error_result.reset() self._closed_result.reset()
'Context manager that controls access to event dispatcher for preventing reentrancy. The "as" value is True if the managed code block owns the event dispatcher and False if caller higher up in the call stack already owns it. Only managed code that gets ownership (got True) is permitted to dispatch'
@contextlib.contextmanager def _acquire_event_dispatch(self):
try: self._event_dispatch_suspend_depth += 1 (yield (self._event_dispatch_suspend_depth == 1)) finally: self._event_dispatch_suspend_depth -= 1
'Perform follow-up processing for connection setup request: flush connection output and process input while waiting for connection-open or connection-error. :raises AMQPConnectionError: on connection open error'
def _process_io_for_connection_setup(self):
if (not self._open_error_result.ready): self._flush_output(self._opened_result.is_ready, self._open_error_result.is_ready) if self._open_error_result.ready: try: exception_or_message = self._open_error_result.value.error if isinstance(exception_or_message, Exception): ...
'Flush output and process input while waiting for any of the given callbacks to return true. The wait is aborted upon connection-close. Otherwise, processing continues until the output is flushed AND at least one of the callbacks returns true. If there are no callbacks, then processing ends when all output is flushed. ...
def _flush_output(self, *waiters):
if self.is_closed: raise exceptions.ConnectionClosed() is_done = (lambda : (self._closed_result.ready or ((not self._impl.outbound_buffer) and ((not waiters) or any((ready() for ready in waiters)))))) while (not is_done()): self._impl.ioloop.poll() self._impl.ioloop.process_timeouts(...
'Called by BlockingChannel instances to request a call to their _dispatch_events method or to terminate `process_data_events`; BlockingConnection will honor these requests from a safe context. :param int channel_number: positive channel number to request a call to the channel\'s `_dispatch_events`; a negative channel n...
def _request_channel_dispatch(self, channel_number):
self._channels_pending_dispatch.add(channel_number)
'Invoke the `_dispatch_events` method on open channels that requested it'
def _dispatch_channel_events(self):
if (not self._channels_pending_dispatch): return with self._acquire_event_dispatch() as dispatch_acquired: if (not dispatch_acquired): return candidates = list(self._channels_pending_dispatch) self._channels_pending_dispatch.clear() for channel_number in candi...
'Handle expiry of a timer that was registered via `add_timeout` :param _TimerEvt evt:'
def _on_timer_ready(self, evt):
self._ready_events.append(evt)
'Handle Connection.Blocked notification from RabbitMQ broker :param callable user_callback: callback_method passed to `add_on_connection_blocked_callback` :param pika.frame.Method method_frame: method frame having `method` member of type `pika.spec.Connection.Blocked`'
def _on_connection_blocked(self, user_callback, method_frame):
self._ready_events.append(_ConnectionBlockedEvt(user_callback, method_frame))
'Handle Connection.Unblocked notification from RabbitMQ broker :param callable user_callback: callback_method passed to `add_on_connection_unblocked_callback` :param pika.frame.Method method_frame: method frame having `method` member of type `pika.spec.Connection.Blocked`'
def _on_connection_unblocked(self, user_callback, method_frame):
self._ready_events.append(_ConnectionUnblockedEvt(user_callback, method_frame))
'Dispatch ready connection events'
def _dispatch_connection_events(self):
if (not self._ready_events): return with self._acquire_event_dispatch() as dispatch_acquired: if (not dispatch_acquired): return for _ in compat.xrange(len(self._ready_events)): try: evt = self._ready_events.popleft() except IndexError:...
'Add a callback to be notified when RabbitMQ has sent a `Connection.Blocked` frame indicating that RabbitMQ is low on resources. Publishers can use this to voluntarily suspend publishing, instead of relying on back pressure throttling. The callback will be passed the `Connection.Blocked` method frame. See also `Connect...
def add_on_connection_blocked_callback(self, callback_method):
self._impl.add_on_connection_blocked_callback(functools.partial(self._on_connection_blocked, callback_method))
'Add a callback to be notified when RabbitMQ has sent a `Connection.Unblocked` frame letting publishers know it\'s ok to start publishing again. The callback will be passed the `Connection.Unblocked` method frame. :param method callback_method: Callback to call on `Connection.Unblocked`, having the signature `callback_...
def add_on_connection_unblocked_callback(self, callback_method):
self._impl.add_on_connection_unblocked_callback(functools.partial(self._on_connection_unblocked, callback_method))
'Create a single-shot timer to fire after deadline seconds. Do not confuse with Tornado\'s timeout where you pass in the time you want to have your callback called. Only pass in the seconds until it\'s to be called. NOTE: the timer callbacks are dispatched only in the scope of specially-designated methods: see `Blockin...
def add_timeout(self, deadline, callback_method):
if (not callable(callback_method)): raise ValueError(('callback_method parameter must be callable, but got %r' % (callback_method,))) evt = _TimerEvt(callback=callback_method) timer_id = self._impl.add_timeout(deadline, functools.partial(self._on_timer_ready, evt)) evt.timer...
'Remove a timer if it\'s still in the timeout stack :param timeout_id: The opaque timer id to remove'
def remove_timeout(self, timeout_id):
self._impl.remove_timeout(timeout_id) for (i, evt) in enumerate(self._ready_events): if (isinstance(evt, _TimerEvt) and (evt.timer_id == timeout_id)): index_to_remove = i break else: return del self._ready_events[index_to_remove]
'Disconnect from RabbitMQ. If there are any open channels, it will attempt to close them prior to fully disconnecting. Channels which have active consumers will attempt to send a Basic.Cancel to RabbitMQ to cleanly stop the delivery of messages prior to closing the channel. :param int reply_code: The code number for th...
def close(self, reply_code=200, reply_text='Normal shutdown'):
if self.is_closed: LOGGER.debug('Close called on closed connection (%s): %s', reply_code, reply_text) return LOGGER.info('Closing connection (%s): %s', reply_code, reply_text) self._user_initiated_close = True for impl_channel in pika.compat.dictvalues(self._im...
'Will make sure that data events are processed. Dispatches timer and channel callbacks if not called from the scope of BlockingConnection or BlockingChannel callback. Your app can block on this method. :param float time_limit: suggested upper bound on processing time in seconds. The actual blocking time depends on the ...
def process_data_events(self, time_limit=0):
with self._acquire_event_dispatch() as dispatch_acquired: common_terminator = (lambda : bool((dispatch_acquired and (self._channels_pending_dispatch or self._ready_events)))) if (time_limit is None): self._flush_output(common_terminator) else: with _IoloopTimerContext...
'A safer way to sleep than calling time.sleep() directly that would keep the adapter from ignoring frames sent from the broker. The connection will "sleep" or block the number of seconds specified in duration in small intervals. :param float duration: The time to sleep in seconds'
def sleep(self, duration):
assert (duration >= 0), duration deadline = (time.time() + duration) time_limit = duration while True: self.process_data_events(time_limit) time_limit = (deadline - time.time()) if (time_limit <= 0): break
'Create a new channel with the next available channel number or pass in a channel number to use. Must be non-zero if you would like to specify but it is recommended that you let Pika manage the channel numbers. :rtype: pika.adapters.blocking_connection.BlockingChannel'
def channel(self, channel_number=None):
with _CallbackResult(self._OnChannelOpenedArgs) as opened_args: impl_channel = self._impl.channel(on_open_callback=opened_args.set_value_once, channel_number=channel_number) channel = BlockingChannel(impl_channel, self) impl_channel._set_cookie(channel) channel._flush_output(opened_a...
'Returns a boolean reporting the current connection state.'
@property def is_closed(self):
return self._impl.is_closed
'Returns True if connection is in the process of closing due to client-initiated `close` request, but closing is not yet complete.'
@property def is_closing(self):
return self._impl.is_closing
'Returns a boolean reporting the current connection state.'
@property def is_open(self):
return self._impl.is_open
'Specifies if the server supports basic.nack on the active connection. :rtype: bool'
@property def basic_nack_supported(self):
return self._impl.basic_nack
'Specifies if the server supports consumer cancel notification on the active connection. :rtype: bool'
@property def consumer_cancel_notify_supported(self):
return self._impl.consumer_cancel_notify
'Specifies if the active connection supports exchange to exchange bindings. :rtype: bool'
@property def exchange_exchange_bindings_supported(self):
return self._impl.exchange_exchange_bindings
'Specifies if the active connection can use publisher confirmations. :rtype: bool'
@property def publisher_confirms_supported(self):
return self._impl.publisher_confirms
':param spec.Basic.Deliver method: NOTE: consumer_tag and delivery_tag are valid only within source channel :param spec.BasicProperties properties: message properties :param body: message body; empty string if no body :type body: str or unicode'
def __init__(self, method, properties, body):
self.method = method self.properties = properties self.body = body
':param pika.frame.Method method_frame: method frame with method of type `spec.Basic.Cancel`'
def __init__(self, method_frame):
self.method_frame = method_frame
'method of type spec.Basic.Cancel'
@property def method(self):
return self.method_frame.method
':param callable callback: user\'s callback, having the signature callback(channel, method, properties, body), where channel: pika.Channel method: pika.spec.Basic.Return properties: pika.spec.BasicProperties body: str, unicode, or bytes (python 3.x) :param pika.Channel channel: :param pika.spec.Basic.Return method: :pa...
def __init__(self, callback, channel, method, properties, body):
self.callback = callback self.channel = channel self.method = method self.properties = properties self.body = body
'Dispatch user\'s callback'
def dispatch(self):
self.callback(self.channel, self.method, self.properties, self.body)
':param spec.Basic.Return method: :param spec.BasicProperties properties: message properties :param body: message body; empty string if no body :type body: str or unicode'
def __init__(self, method, properties, body):
self.method = method self.properties = properties self.body = body
'NOTE: exactly one of consumer_cb/alternate_event_sink musts be non-None. :param str consumer_tag: :param bool no_ack: the no-ack value for the consumer :param callable consumer_cb: The function for dispatching messages to user, having the signature: consumer_callback(channel, method, properties, body) channel: Blockin...
def __init__(self, consumer_tag, no_ack, consumer_cb=None, alternate_event_sink=None):
assert ((consumer_cb is None) != (alternate_event_sink is None)), ('exactly one of consumer_cb/alternate_event_sink must be non-None', consumer_cb, alternate_event_sink) self.consumer_tag = consumer_tag self.no_ack = no_ack self.consumer_cb = consumer_cb self.alternate_event_sink =...
'True if in SETTING_UP state'
@property def setting_up(self):
return (self.state == self.SETTING_UP)
'True if in ACTIVE state'
@property def active(self):
return (self.state == self.ACTIVE)
'True if in TEARING_DOWN state'
@property def tearing_down(self):
return (self.state == self.TEARING_DOWN)
'True if in CANCELLED_BY_BROKER state'
@property def cancelled_by_broker(self):
return (self.state == self.CANCELLED_BY_BROKER)
':params tuple params: a three-tuple (queue, no_ack, exclusive) that were used to create the queue consumer :param str consumer_tag: consumer tag'
def __init__(self, params, consumer_tag):
self.params = params self.consumer_tag = consumer_tag self.pending_events = deque()
'Create a new instance of the Channel :param channel_impl: Channel implementation object as returned from SelectConnection.channel() :param BlockingConnection connection: The connection object'
def __init__(self, channel_impl, connection):
self._impl = channel_impl self._connection = connection self._consumer_infos = dict() self._queue_consumer_generator = None self._delivery_confirmation = False self._message_confirmation_result = _CallbackResult(self._OnMessageConfirmationReportArgs) self._pending_events = deque() self._...
'Return the channel object as its channel number NOTE: inherited from legacy BlockingConnection; might be error-prone; use `channel_number` property instead. :rtype: int'
def __int__(self):
return self.channel_number
'Clean up members that might inhibit garbage collection'
def _cleanup(self):
self._message_confirmation_result.reset() self._pending_events = deque() self._consumer_infos = dict()
'Channel number'
@property def channel_number(self):
return self._impl.channel_number
'The channel\'s BlockingConnection instance'
@property def connection(self):
return self._connection
'Returns True if the channel is closed. :rtype: bool'
@property def is_closed(self):
return self._impl.is_closed
'Returns True if client-initiated closing of the channel is in progress. :rtype: bool'
@property def is_closing(self):
return self._impl.is_closing
'Returns True if the channel is open. :rtype: bool'
@property def is_open(self):
return self._impl.is_open
'Flush output and process input while waiting for any of the given callbacks to return true. The wait is aborted upon channel-close or connection-close. Otherwise, processing continues until the output is flushed AND at least one of the callbacks returns true. If there are no callbacks, then processing ends when all ou...
def _flush_output(self, *waiters):
if self.is_closed: raise exceptions.ChannelClosed() if (not waiters): waiters = self._ALWAYS_READY_WAITERS self._connection._flush_output(self._channel_closed_by_broker_result.is_ready, *waiters) if self._channel_closed_by_broker_result: self._cleanup() method = self._cha...
'Called as the result of Basic.Return from broker in publisher-acknowledgements mode. Saves the info as a ReturnedMessage instance in self._puback_return. :param pika.Channel channel: our self._impl channel :param pika.spec.Basic.Return method: :param pika.spec.BasicProperties properties: message properties :param body...
def _on_puback_message_returned(self, channel, method, properties, body):
assert (channel is self._impl), (channel.channel_number, self.channel_number) assert isinstance(method, pika.spec.Basic.Return), method assert isinstance(properties, pika.spec.BasicProperties), properties LOGGER.warn('Published message was returned: _delivery_confirmation=%s; channel=%s; ...
'Append an event to the channel\'s list of events that are ready for dispatch to user and signal our connection that this channel is ready for event dispatch :param _ChannelPendingEvt evt: an event derived from _ChannelPendingEvt'
def _add_pending_event(self, evt):
self._pending_events.append(evt) self.connection._request_channel_dispatch(self.channel_number)
'Called by impl when broker cancels consumer via Basic.Cancel. This is a RabbitMQ-specific feature. The circumstances include deletion of queue being consumed as well as failure of a HA node responsible for the queue being consumed. :param pika.frame.Method method_frame: method frame with the `spec.Basic.Cancel` method...
def _on_consumer_cancelled_by_broker(self, method_frame):
evt = _ConsumerCancellationEvt(method_frame) consumer = self._consumer_infos[method_frame.method.consumer_tag] if (not consumer.tearing_down): consumer.state = _ConsumerInfo.CANCELLED_BY_BROKER if (consumer.alternate_event_sink is not None): consumer.alternate_event_sink(evt) else: ...
'Called by impl when a message is delivered for a consumer :param Channel channel: The implementation channel object :param spec.Basic.Deliver method: :param pika.spec.BasicProperties properties: message properties :param body: delivered message body; empty string if no body :type body: str, unicode, or bytes (python 3...
def _on_consumer_message_delivery(self, _channel, method, properties, body):
evt = _ConsumerDeliveryEvt(method, properties, body) consumer = self._consumer_infos[method.consumer_tag] if (consumer.alternate_event_sink is not None): consumer.alternate_event_sink(evt) else: self._add_pending_event(evt)
'Sink for the queue consumer generator\'s consumer events; append the event to queue consumer generator\'s pending events buffer. :param evt: an object of type _ConsumerDeliveryEvt or _ConsumerCancellationEvt'
def _on_consumer_generator_event(self, evt):
self._queue_consumer_generator.pending_events.append(evt) self.connection._request_channel_dispatch((- self.channel_number))
'Cancel all consumers. NOTE: pending non-ackable messages will be lost; pending ackable messages will be rejected.'
def _cancel_all_consumers(self):
if self._consumer_infos: LOGGER.debug('Cancelling %i consumers', len(self._consumer_infos)) if (self._queue_consumer_generator is not None): self.cancel() for consumer_tag in pika.compat.dictkeys(self._consumer_infos): self.basic_cancel(consumer_tag)
'Called by BlockingConnection to dispatch pending events. `BlockingChannel` schedules this callback via `BlockingConnection._request_channel_dispatch`'
def _dispatch_events(self):
while self._pending_events: evt = self._pending_events.popleft() if (type(evt) is _ConsumerDeliveryEvt): consumer_info = self._consumer_infos[evt.method.consumer_tag] consumer_info.consumer_cb(self, evt.method, evt.properties, evt.body) elif (type(evt) is _ConsumerCan...
'Will invoke a clean shutdown of the channel with the AMQP Broker. :param int reply_code: The reply code to close the channel with :param str reply_text: The reply text to close the channel with'
def close(self, reply_code=0, reply_text='Normal shutdown'):
LOGGER.debug('Channel.close(%s, %s)', reply_code, reply_text) self._cancel_all_consumers() try: with _CallbackResult() as close_ok_result: self._impl.add_callback(callback=close_ok_result.signal_once, replies=[pika.spec.Channel.CloseOk], one_shot=True) self._impl.close(rep...
'Turn Channel flow control off and on. NOTE: RabbitMQ doesn\'t support active=False; per https://www.rabbitmq.com/specification.html: "active=false is not supported by the server. Limiting prefetch with basic.qos provides much better control" For more information, please reference: http://www.rabbitmq.com/amqp-0-9-1-re...
def flow(self, active):
with _CallbackResult(self._FlowOkCallbackResultArgs) as flow_ok_result: self._impl.flow(callback=flow_ok_result.set_value_once, active=active) self._flush_output(flow_ok_result.is_ready) return flow_ok_result.value.active
'Pass a callback function that will be called when Basic.Cancel is sent by the broker. The callback function should receive a method frame parameter. :param callable callback: a callable for handling broker\'s Basic.Cancel notification with the call signature: callback(method_frame) where method_frame is of type `pika....
def add_on_cancel_callback(self, callback):
self._impl.callbacks.add(self.channel_number, self._CONSUMER_CANCELLED_CB_KEY, callback, one_shot=False)
'Pass a callback function that will be called when a published message is rejected and returned by the server via `Basic.Return`. :param callable callback: The method to call on callback with the signature callback(channel, method, properties, body), where channel: pika.Channel method: pika.spec.Basic.Return properties...
def add_on_return_callback(self, callback):
self._impl.add_on_return_callback((lambda _channel, method, properties, body: self._add_pending_event(_ReturnedMessageEvt(callback, self, method, properties, body))))
'Sends the AMQP command Basic.Consume to the broker and binds messages for the consumer_tag to the consumer callback. If you do not pass in a consumer_tag, one will be automatically generated for you. Returns the consumer tag. NOTE: the consumer callbacks are dispatched only in the scope of specially-designated methods...
def basic_consume(self, consumer_callback, queue, no_ack=False, exclusive=False, consumer_tag=None, arguments=None):
if (not callable(consumer_callback)): raise ValueError(('consumer callback must be callable; got %r' % consumer_callback)) return self._basic_consume_impl(queue=queue, no_ack=no_ack, exclusive=exclusive, consumer_tag=consumer_tag, arguments=arguments, consumer_callback=consumer_callbac...
'The low-level implementation used by `basic_consume` and `consume`. See `basic_consume` docstring for more info. NOTE: exactly one of consumer_callback/alternate_event_sink musts be non-None. This method has one additional parameter alternate_event_sink over the args described in `basic_consume`. :param callable alter...
def _basic_consume_impl(self, queue, no_ack, exclusive, consumer_tag, arguments=None, consumer_callback=None, alternate_event_sink=None):
if ((consumer_callback is None) == (alternate_event_sink is None)): raise ValueError(('exactly one of consumer_callback/alternate_event_sink must be non-None', consumer_callback, alternate_event_sink)) if (not consumer_tag): consumer_tag = self._impl._generate_consumer_tag() ...
'This method cancels a consumer. This does not affect already delivered messages, but it does mean the server will not send any more messages for that consumer. The client may receive an arbitrary number of messages in between sending the cancel method and receiving the cancel-ok reply. NOTE: When cancelling a no_ack=F...
def basic_cancel(self, consumer_tag):
try: consumer_info = self._consumer_infos[consumer_tag] except KeyError: LOGGER.warn('User is attempting to cancel an unknown consumer=%s; already cancelled by user or broker?', consumer_tag) return [] try: assert (consumer_info.active o...
'Extract _ConsumerDeliveryEvt objects destined for the given consumer from pending events, discarding the _ConsumerCancellationEvt, if any :param str consumer_tag: :returns: a (possibly empty) sequence of _ConsumerDeliveryEvt destined for the given consumer tag'
def _remove_pending_deliveries(self, consumer_tag):
remaining_events = deque() unprocessed_messages = [] while self._pending_events: evt = self._pending_events.popleft() if (type(evt) is _ConsumerDeliveryEvt): if (evt.method.consumer_tag == consumer_tag): unprocessed_messages.append(evt) continue ...
'Processes I/O events and dispatches timers and `basic_consume` callbacks until all consumers are cancelled. NOTE: this blocking function may not be called from the scope of a pika callback, because dispatching `basic_consume` callbacks from this context would constitute recursion. :raises pika.exceptions.RecursionErro...
def start_consuming(self):
with self.connection._acquire_event_dispatch() as dispatch_allowed: if (not dispatch_allowed): raise exceptions.RecursionError('start_consuming may not be called from the scope of another BlockingConnection or BlockingChannel callback') while self._cons...
'Cancels all consumers, signalling the `start_consuming` loop to exit. NOTE: pending non-ackable messages will be lost; pending ackable messages will be rejected.'
def stop_consuming(self, consumer_tag=None):
if consumer_tag: self.basic_cancel(consumer_tag) else: self._cancel_all_consumers()
'Blocking consumption of a queue instead of via a callback. This method is a generator that yields each message as a tuple of method, properties, and body. The active generator iterator terminates when the consumer is cancelled by client or broker. Example: for method, properties, body in channel.consume(\'queue\'): pr...
def consume(self, queue, no_ack=False, exclusive=False, arguments=None, inactivity_timeout=None):
params = (queue, no_ack, exclusive) if (self._queue_consumer_generator is not None): if (params != self._queue_consumer_generator.params): raise ValueError(('Consume with different params not allowed on existing queue consumer generator; previous params: ...
'Returns the number of messages that may be retrieved from the current queue consumer generator via `BlockingChannel.consume` without blocking. NEW in pika 0.10.0 :rtype: int'
def get_waiting_message_count(self):
if (self._queue_consumer_generator is not None): pending_events = self._queue_consumer_generator.pending_events count = len(pending_events) if (count and (type(pending_events[(-1)]) is _ConsumerCancellationEvt)): count -= 1 else: count = 0 return count
'Cancel the queue consumer created by `BlockingChannel.consume`, rejecting all pending ackable messages. NOTE: If you\'re looking to cancel a consumer issued with BlockingChannel.basic_consume then you should call BlockingChannel.basic_cancel. :return int: The number of messages requeued by Basic.Nack. NEW in 0.10.0: r...
def cancel(self):
if (self._queue_consumer_generator is None): LOGGER.warning('cancel: queue consumer generator is inactive (already cancelled by client or broker?)') return 0 try: (_, no_ack, _) = self._queue_consumer_generator.params if (not no_ack): ...
'Acknowledge one or more messages. When sent by the client, this method acknowledges one or more messages delivered via the Deliver or Get-Ok methods. When sent by server, this method acknowledges one or more messages published with the Publish method on a channel in confirm mode. The acknowledgement can be for a singl...
def basic_ack(self, delivery_tag=0, multiple=False):
self._impl.basic_ack(delivery_tag=delivery_tag, multiple=multiple) self._flush_output()
'This method allows a client to reject one or more incoming messages. It can be used to interrupt and cancel large incoming messages, or return untreatable messages to their original queue. :param int delivery-tag: The server-assigned delivery tag :param bool multiple: If set to True, the delivery tag is treated as "up...
def basic_nack(self, delivery_tag=None, multiple=False, requeue=True):
self._impl.basic_nack(delivery_tag=delivery_tag, multiple=multiple, requeue=requeue) self._flush_output()
'Get a single message from the AMQP broker. Returns a sequence with the method frame, message properties, and body. :param queue: Name of queue to get a message from :type queue: str or unicode :param bool no_ack: Tell the broker to not expect a reply :returns: a three-tuple; (None, None, None) if the queue was empty; ...
def basic_get(self, queue=None, no_ack=False):
assert (not self._basic_getempty_result) with _CallbackResult(self._RxMessageArgs) as get_ok_result: with self._basic_getempty_result: self._impl.basic_get(callback=get_ok_result.set_value_once, queue=queue, no_ack=no_ack) self._flush_output(get_ok_result.is_ready, self._basic_ge...