how to get the queue in which a task was run - celery

两盒软妹~` 提交于 2020-01-13 14:05:12

问题


I'm new using celery and have a question. I have this simple task:

@app.task(name='test_install_queue')
def test_install_queue():
    return subprocess.call("exit 0",shell=True)

and I am calling this task later in a test case like

result = tasks.test_default_queue.apply_async(queue="install")

The task run successfully in the queue install (because I am seeing it in the celery log, and it completes fine. But I would like to know a programmatically way of finding in which queue was the task test_install_queue run, from the object stored in result.

Thank you!

EDIT:

I've changed the tasks to be like:

@app.task(name='test_install_queue',bind=True)
def test_install_queue(self):
    return self.request.__dict__

and then I'm using the result of apply_async as follows:

result = tasks.test_install_queue.apply_async(queue="install")
assert "install" in result.get()["hostname"]

and the workaround is that the worker (hostname) has the same name as the only queue that is initialized in the worker.


回答1:


You can try the following approach:

delivery_info = app.current_task.request.delivery_info
# by default celery uses the same name for queues and exchanges
original_queue = delivery_info['exchange']
for queue in app.amqp.queues.itervalues():
    if queue.exchange.name == delivery_info['exchange'] 
        and queue.routing_key == delivery_info['routing_key']:
            original_queue = queue.name
            break

That approach is built on assumption that you use default celery settings and your exchanges are direct. If you need more universal solution for fanout and topic exchanges then you will have to check routing keys of every declared queue in app.amqp.queues.



来源:https://stackoverflow.com/questions/22385297/how-to-get-the-queue-in-which-a-task-was-run-celery

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!