Python 如何获取运行任务的队列-芹菜

Python 如何获取运行任务的队列-芹菜,python,queue,task,celery,Python,Queue,Task,Celery,我刚开始用芹菜,有个问题。我有一个简单的任务: @app.task(name='test_install_queue') def test_install_queue(): return subprocess.call("exit 0",shell=True) 稍后我在一个测试用例中调用这个任务,比如 result = tasks.test_default_queue.apply_async(queue="install") 任务在队列install中成功运行(因为我在芹菜日志中看到

我刚开始用芹菜,有个问题。我有一个简单的任务:

@app.task(name='test_install_queue')
def test_install_queue():
    return subprocess.call("exit 0",shell=True)
稍后我在一个测试用例中调用这个任务,比如

result = tasks.test_default_queue.apply_async(queue="install")
任务在队列
install
中成功运行(因为我在芹菜日志中看到了它,并且它完成得很好。但是我想知道一种通过编程的方式,从
result
中存储的对象中查找任务
test\u install\u queue
运行在哪个队列中

谢谢大家!

编辑:

我已将任务更改为:

@app.task(name='test_install_queue',bind=True)
def test_install_queue(self):
    return self.request.__dict__
然后我使用
apply\u async
的结果如下:

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

解决方法是工作线程(主机名)与工作线程中唯一初始化的队列同名。

您可以尝试以下方法:

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

这种方法是建立在假设您使用默认芹菜设置并且您的交换是直接的基础上的。如果您需要更通用的扇出和主题交换解决方案,那么您必须检查
app.amqp.queues

中每个声明队列的路由键,我自己也刚刚遇到过这个问题,而且我真的对n表示怀疑一个复杂的解决方案的需求,如一个从“lexabug”已被接受。。。 因此,因为即使芹菜文档也不能提供有效的替代方案,所以我自己使用反射进行了调查,以了解哪个对象包含我需要的信息,我想出了一个非常简单和直接的解决方案。具体地说,我在写一个钩子,或者更好,芹菜术语的信号,我就是这样重试的根据任务名称指定队列的名称:

    @signals.after_task_publish.connect()
    def on_task_publish(sender=None, headers=None, body=None, **kwargs):

        # "sender" is a string containing task name 
        # ("celery" here is the celery app)
        task: Task = celery.tasks.get(sender)

        # once we have the task object, we can access the "queue" property 
        # which contains the name of the queue 
        # (it' a dynamic property so don't expect support by your IDE)
        queue_name: str = task.queue if task is not None else 'unknown'

另外,我正在使用芹菜4.4

这可能会有所帮助:谢谢。但我不需要任务ID,我需要任务运行的队列。我阅读了芹菜文档,但没有找到任何内容。请参阅该部分中的链接->仅供参考,如果您没有为任务指定名称,它将与函数名相同,因此在您的考试中ple任务名称是不必要的。此外,如果每个任务始终在同一个队列中,您可以为其指定队列,而不是调用它。因此它将类似于:
@app.task(queue='install')
。谢谢你们。问题不在于队列或路由,我想尝试从芹菜工人那里获取队列名称(我正在静态设置队列,以确保我将“以编程方式”获取的队列是正确的。我最终能够解决问题,但您的答案仍然有效。谢谢!“我真的怀疑是否需要复杂的解决方案”我也非常怀疑这种需要,但老实说,即使在挖掘芹菜和kombu代码库一段时间后,我也不清楚为什么
delivery\u info
不存在,或者为什么钩子中的
queue
exchange
etc值为空。不过,谢谢你。