我想将我的代码从
sync
重构为 async
。我使用 Python 和 FastAPI。
我使用在枚举中调用 async
函数的方法。
例如:
from enum import Enum
from app.story import get_story
StoriesEnum = Enum(
"StoriesEnum", {story: story for story in get_story.story_list},
)
get_story
是一个 async
函数,返回 Story
类,并且它具有 story_list
。
我怎样才能
await
get_story.story_list
?
我尝试过:
asyncio.run()
get_event_loop()
async
发电机没有成功的结果。它们不起作用,因为
await
位于 async
函数之外。
根据文档:
您可能已经注意到,
只能在函数内部使用 用await
定义。async def
但同时,用
定义的函数必须是 “等待”。因此,具有async def
的函数只能在 内部调用 也用async def
定义函数。async def
因此,你可以做的是:
import asyncio
async def go():
return Enum("StoriesEnum", {s:s for s in (await get_story()).story_list.value})
StoriesEnum = asyncio.run(go())
print({e:e.value for e in StoriesEnum})
请查看这个答案,了解有关 FastAPI 和 Python 中的
async
/ await
的更多详细信息。