且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

我如何在 asyncio 中使用请求?

更新时间:2022-06-07 23:26:44

要将请求(或任何其他阻塞库)与 asyncio 一起使用,您可以使用 BaseEventLoop.run_in_executor 在另一个线程中运行一个函数并从中产生结果以获得结果.例如:

To use requests (or any other blocking libraries) with asyncio, you can use BaseEventLoop.run_in_executor to run a function in another thread and yield from it to get the result. For example:

import asyncio
import requests

@asyncio.coroutine
def main():
    loop = asyncio.get_event_loop()
    future1 = loop.run_in_executor(None, requests.get, 'http://www.google.com')
    future2 = loop.run_in_executor(None, requests.get, 'http://www.google.co.uk')
    response1 = yield from future1
    response2 = yield from future2
    print(response1.text)
    print(response2.text)

loop = asyncio.get_event_loop()
loop.run_until_complete(main())

这将同时获得两个响应.

This will get both responses in parallel.

在 python 3.5 中,您可以使用新的 await/async 语法:

With python 3.5 you can use the new await/async syntax:

import asyncio
import requests

async def main():
    loop = asyncio.get_event_loop()
    future1 = loop.run_in_executor(None, requests.get, 'http://www.google.com')
    future2 = loop.run_in_executor(None, requests.get, 'http://www.google.co.uk')
    response1 = await future1
    response2 = await future2
    print(response1.text)
    print(response2.text)

loop = asyncio.get_event_loop()
loop.run_until_complete(main())

有关更多信息,请参阅 PEP0492.

See PEP0492 for more.