我正在尝试使用数据迁移来填充我的数据库,但是我面对的是RuntimeWarning,并且数据没有被插入。
在填充函数中,我尝试以这种方式在api调用中使用Async Await:
async def populate_table(apps, schema_editor):
some stuff...
await api_call_1()...
for i in range():
await api_call_2()... #an api call inside a for loop (Async inside Sync is ok?)#
model.save()然后,我在我的迁移类中:
class Migration(migrations.Migration):
dependencies = [
('myapp', 'the previous migration'),
]
operations = [
migrations.RunPython(populate_table)
]运行迁移时将引发运行时警告:
RuntimeWarning: coroutine 'populate_table' was never awaited所以我尝试用Async/Await来装饰我的Migration类,但没有成功。我做了一些研究,似乎我需要使用事件循环。如何做到这一点?
发布于 2021-03-04 06:15:22
这似乎是一种使用asgiref的async_to_sync和sync_to_async工作的方法:
from asgiref.sync import async_to_sync, sync_to_async
@async_to_sync
async def forward_func(apps, schema_editor):
await api_call_1()
for i in range():
await api_call_2()
await sync_to_async(model.save)()需要访问数据库的同步函数应该包装在sync_to_async中,然后等待。
这可能有点单调乏味,所以分离异步代码可能是一种好方法,如下所示:
def forward_func(apps, schema_editor):
@async_to_sync
def get_data_from_the_api():
...
api_data = get_data_from_the_api()
...
model.save()https://stackoverflow.com/questions/60220433
复制相似问题