Django 异步与 AppConfig.ready 同步/异步

问题描述 投票:0回答:1

我正在异步模式下运行 Django 版本 4.2.4。对于我的一个应用程序,我有一些代码可以像这样运行:

class CoreConfig(AppConfig):
    name = 'demo.core'

    def ready(self):
        from .utils import my_sync_func
        my_sync_func()

当我运行此代码时,我收到警告“RuntimeWarning:协程‘CoreConfig.ready’从未等待”

当我像这样使用sync_to_async时:

class CoreConfig(AppConfig):
    name = 'demo.core'

    async def ready(self):
        from .utils import my_sync_func
        await sync_to_async(my_sync_func)()

我收到警告“RuntimeWarning:协程‘CoreConfig.ready’从未等待”

这样做的正确方法是什么?

非常感谢

django asynchronous ready
1个回答
0
投票

这是一个令人悲伤的问题;目前(直到 Django 5.0),无法在

ready
方法内运行异步代码。您可以尝试使用
async_to_sync
中的
asgiref
功能,但在开发服务器以外的其他环境中会失败,例如Uvicorn。

看看启动时如何调用

Apps.ready()
方法,就很明显了。

https://github.com/django/django/blob/42bc81b1b6471c4fe364bc32b9dec180908e577e/django/apps/registry.py#L122

© www.soinside.com 2019 - 2024. All rights reserved.