python-3.x - Await a method and assign a variable to the returned value with asyncio?
问题描述
I'm using asyncio with requests to try to make a core module asynchronous program. I've ran into a difficulty when trying to do something like this
import asyncio
import requests
async def main():
await r = requests.get(URL)
What I thought this would do is wait for the get request to finish, then take the return value and put it in r, but this error happens
File "prog.py", line 20
await r = requests.get(URL)
^
SyntaxError: can't assign to await expression
r = await requests.get(URL) doesn't seem to work either, giving
prog.py:31: RuntimeWarning: coroutine 'coroutine' was never awaited
coroutine(args)
Does anyone know how to do this?
解决方案
How to use await
?
await
can be used only to await coroutine
- special object returned by calling function defined with async def
:
import asyncio
async def test():
return True
async def main():
# test() returns coroutine:
coro = test()
print(coro) # <coroutine object test at ...>
# we can await for coroutine to get result:
res = await coro
print(res) # True
if __name__ == '__main__':
loop = asyncio.get_event_loop()
loop.run_until_complete(main())
Read also this answer about using asyncio
.
Why await requests.get(URL)
doesn't work?
Because requests.get
is not a coroutine (it's not defined with async def
), it's regular function by nature.
If you want to make request asynchronously you should either use special async module like aiohttp
for this or wrap requests
into coroutine using threads. See code snippets here for both examples.
推荐阅读
- tabulator - 将标题设置为计算总和
- python - 列表python中的itertool组动态元素
- javascript - 从chrome中的父选项卡设置角度应用程序的标题
- c# - 如何管理超过 1 个资源?
- notion-api - Notion API - 使用 Notion OAuth 或 API 令牌创建数据库
- javascript - 根据手机屏幕大小处理网站滚动偏移
- excel - VBA 代码从重叠的不连续数组创建 2 个图形
- facebook-graph-api - Facebook Marketing API 展示位置资产自定义asset_feed_spec 错误
- arrays - 在 C 中创建和释放 3D 数组的内存
- java - 通过 Spring Cloud Netflix 访问服务的端点 /actuator/health:Zuul