def task_process(self, channel: BlockingChannel, method: Basic.Deliver, properties: BasicProperties, body: bytes) -> None: """ Process the received task :param channel: channel :param method: method :param properties: task properties :param body: task body :return: None """ raw_body = loads(body.decode(encoding="utf-8")) cases = raw_body.get("cases", {}) task = TaskItem(**raw_body.get("task", {})) try: results = list(self.manager.multi_case_runner(cases=cases)) for result in results: TaskCrud.create_task_result(task, result or {}) task.set_success( msg=f"Task done: {len(results)} out of {len(cases)} cases") except Exception as cases_err: task.set_error(msg=f"Task error: {str(cases_err)}") TaskCrud.update_task(task) logger.info(msg=f"Done task {task.task_id}") channel.basic_publish( exchange="", routing_key=properties.reply_to, properties=BasicProperties( correlation_id=properties.correlation_id), body=dumps(task.as_json()).encode(encoding="utf-8"), ) channel.basic_ack(delivery_tag=method.delivery_tag)
def gracefully_stop_runner(channel: BlockingChannel, count: int): runners = db.get_collection('corp-hq', 'runners') all_runners = list(runners.find()) for i in range(count): runner = all_runners[i] channel.basic_publish(exchange='', routing_key=runner['name'], body='') LOG.info('Request for runner "%s" to stop sent.', runner['name'])
def send_message_to( self, exchange_name: str, ch: BlockingChannel, routing_key: str, properties: BasicProperties, body: bytes, ): if properties.headers: redelivery_count = properties.headers.get("redelivery_count", 0) properties.headers["redelivery_count"] = redelivery_count + 1 else: properties.headers = {"redelivery_count": 1} self.printer.print_send_message_to(exchange_name, routing_key, properties.headers) ch.basic_publish( exchange=exchange_name, routing_key=routing_key, body=body, properties=properties, ) return properties.headers
def do_publish(channel: BlockingChannel) -> None: channel.basic_publish( exchange='', routing_key=queue_name, properties=pika.BasicProperties(delivery_mode=2), body=body) statsd.incr(f"rabbitmq.publish.{queue_name}")
def send_message(channel: BlockingChannel, body: str): """ Send a basic message to the given channel :param channel: The channel to send to. :param body: The body to send. """ print(f"Sending message: {body}") channel.basic_publish(exchange="", routing_key=QUEUE_NAME, body=body)
def send_message(channel: BlockingChannel, message: str) -> bool: try: channel.basic_publish(exchange='', routing_key=settings.RABBITMQ_QUEUE, body=bytes(message, encoding='utf-8')) return True except Exception as err: print(err) return False
def on_request(self, channel: BlockingChannel, method, props, body): request = dill.loads(body) response = self.execute_request(request) channel.basic_publish(exchange='', routing_key=props.reply_to, properties=pika.BasicProperties(correlation_id = \ props.correlation_id), body=dill.dumps(response)) channel.basic_ack(delivery_tag=method.delivery_tag)
def publish_message(self, ch: BlockingChannel, msg: str, timestamp: int = None): if not timestamp: timestamp = int(time.time()) ch.basic_publish( exchange="", routing_key=self.queue, body=msg, properties=BasicProperties(delivery_mode=2, timestamp=timestamp), )
def publish(channel: BlockingChannel, message_number: int, mandatory=False, exchange=''): _log.info('publishing message %s', message_number) properties = pika.BasicProperties( content_type='application/json', delivery_mode=pika.spec.PERSISTENT_DELIVERY_MODE, ) channel.basic_publish( exchange=exchange, routing_key='myqueue', properties=properties, mandatory=mandatory, body=json.dumps({'some': message_number}), )
def _instrument_basic_publish( channel: BlockingChannel, tracer: Tracer, publish_hook: utils.HookT = utils.dummy_callback, ) -> None: original_function = getattr(channel, "basic_publish") decorated_function = utils._decorate_basic_publish( original_function, channel, tracer, publish_hook) setattr(decorated_function, "_original_function", original_function) channel.__setattr__("basic_publish", decorated_function) channel.basic_publish = decorated_function
def __on_request( self, channel: BlockingChannel, method: pika.spec.Basic.Deliver, properties: pika.BasicProperties, body: bytes ): try: print('Got message') message = json.loads(body.decode()) print(message) metadata: dict = { 'user': message['user'] if 'user' in message else None } payload: dict = message['payload'] status_code, response = self.methods[message['method']](payload, metadata) print('Response', response) except ResponseException as e: print_exc() status_code, response = e.status_code, str(e) except Exception as e: print_exc() status_code, response = 500, 'Internal Server Error: ' + str(e) if properties.reply_to: channel.basic_publish( exchange='', routing_key=properties.reply_to, properties=pika.BasicProperties(correlation_id=properties.correlation_id), body=json.dumps({ 'statusCode': status_code, 'body': response }) ) else: print('Async, one way, message handled') channel.basic_ack(delivery_tag=method.delivery_tag) print('Acked')
def on_server_rx_rpc_request( self, ch: BlockingChannel, method_frame: Method, properties: Parameters, _body: str, ) -> None: body = dill.loads(_body) logging.info("RPC Server got request: %s", body) res = {"key": body["key"]} try: res["body"] = self._methods[body["method"]](*body["args"], **body["kwargs"]) except Exception as e: logging.exception("Call to %s caused exception", body["method"]) res["exception"] = e ch.basic_publish("", routing_key=properties.reply_to, body=dill.dumps(res)) ch.basic_ack(delivery_tag=method_frame.delivery_tag)