首页 > 解决方案 > 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?

标签: python-3.xpython-asyncio

解决方案


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.


推荐阅读