要将请求(或任何其他阻塞库)与asyncio一起使用,可以使用baseEventLoop.run_in_executor在另一个线程中运行一个函数,并从该线程中屈服以获得结果。例如:
import asyncioimport requests@asyncio.coroutinedef 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())
这将同时获得两个响应。
使用python 3.5可以使用new
await/
async语法:
import asyncioimport requestsasync 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。



