芹菜真的是异步的吗?

Is Celery really async?

我正在使用 celery 和 django-channels 编写实时游戏。

我有一个像定时器一样工作的任务,如果这个定时器达到零,一旦任务被激活,就会调用 group_send()。据我所知,芹菜任务是异步的,但我们不能等待任务中的函数。这让我有点困惑。这是代码:

@app.task(ignore_result=True)
def count_down(channel_name):
    set_random_game_result(channel_name)
    room = process_game_result(channel_name, revoke=False)
    channel_layer = get_channel_layer()
    async_to_sync(channel_layer.group_send)(
        channel_name,
        {
            "type": "game_room_info",
            "room": room
        }
    )

来自文档:

By default the send(), group_send(), group_add() and other functions are async functions, meaning you have to await them. If you need to call them from synchronous code, you’ll need to use the handy asgiref.sync.async_to_sync wrapper

所以如果 celery 是异步的,为什么我不能在不使用 async_to_sync util 的情况下使用 group_send?

另一件事是关于查询.. 来自文档:

If you are writing asynchronous code, however, you will need to call database methods in a safe, synchronous context, using database_sync_to_async.

database_sync_to_async 实际上在任务函数内部不起作用。我错过了什么吗?

您所说的问题是有充分理由设计的。同样是well-documented,只要适当Canvas.

就可以轻松解决

此外...不要混淆术语...Celery 异步的,但它不是"Python async",因为它早于Python的 asyncio...也许 Celery 5 会得到它的异步部分 replaced/refactored 来使用 Python 3+ asyncio 和相关的。