python - 我如何使用 python 协程作为 celery 任务

标签 python celery tornado python-asyncio coroutine

我的 Tornado 项目中有旧的 celery 版本。我当前的 celery 版本是 3.1.23。有一个旧图书馆https://github.com/mher/tornado-celery它现在已经死了,所以我想摆脱它并将 celery 更新到新版本。

我不想更改大量代码,所以我希望能够在我的 celery 任务中使用 async/await 语法。是否可以做这样的事情

@app.task
async def add(x, y):
    res = await some_async_function(x)
    ......

我只看到了同步代码的示例,我不确定我的情况是否适合 celery

任何提示对于 asyncio 或tornado 都有好处。

更新:

尽管 celery 任务已经是异步的,但我需要使用协程的能力。我需要协程,因为目前我们有很多用异步调用编写的任务,这要归功于tornado-celery 库和某种黑魔法。我们通过异步驱动程序进行数据库调用,对 AWS 进行异步调用等。因此,我需要能够在 celery 任务中使用异步语法。例如,我可以在 asyncio 中使用 event_loop.run_until_complete(...) 或在 Tornado 中使用 torchado.ioloop.IOLoop.instance().run_sync(lambda: do_something(1)) ,但这绝对不是更好的方法

最佳答案

据我所知,目前这是不可能的......

Celery 任务无论如何都是异步执行的,所以真的不需要使用协程。 delay()apply_async()send_task() 返回 AsyncResult(类似 future 的对象)。这一切都是有道理的,因为 Celery 早于 Python 的 asyncio 和 async/await,后者后来进入了该语言。

如果你绝对必须使用 async/await,我能想到的唯一解决方案是将你的异步逻辑包装在常规 Celery 任务中。

关于python - 我如何使用 python 协程作为 celery 任务,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57495500/

相关文章:

server - bokeh 服务器,使用 key 生成 session ID

python - 调用 Tornado 服务器时保持 ajax 调用处于事件状态

python - 旋转 PIL 图像似乎没有旋转 Canvas (没有添加 TKinter Canvas )

python - 如何在 PyCharm 中进行远程调试

python - 防止重复的 celery 记录

django - 有没有一种方法可以使用 celery 将消息推送到rabbitmq,而无需在代码中定义任务

redis - 通过 Sentinel 将 Celery 连接到 Redis

python - 何时使用 Tornado,何时使用 Twisted/Cyclone/GEvent/other

python - 如何在 Python 中对字符串进行交叉乘法?

python - 当浏览器到达网页底部时无法退出循环