我怎么能在asyncio中使用请求?
我想在asyncio执行并行http请求任务,但是我发现python-requests会阻塞asyncio的事件循环。 我find了aiohttp,但是无法使用http代理提供http请求服务。 
 所以我想知道是否有一种方法可以在asyncio的帮助下进行asynchronoushttp请求。 
要使用asyncio请求(或任何其他阻塞库),可以使用BaseEventLoop.run_in_executor在另一个线程中运行一个函数,并从中得出结果。 例如:
 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()) 
这将同时得到两个回应。
 用python 3.5你可以使用新的await / async语法: 
 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 。
aiohttp可以和HTTP代理一起使用:
 import asyncio import aiohttp @asyncio.coroutine def do_request(): proxy_url = 'http://localhost:8118' # your proxy address response = yield from aiohttp.request( 'GET', 'http://google.com', proxy=proxy_url, ) return response loop = asyncio.get_event_loop() loop.run_until_complete(do_request()) 
 请求目前不支持asyncio ,也没有计划提供这种支持。 很可能你可以实现一个自定义的“传输适配器”(如这里所讨论的),知道如何使用asyncio 。 
如果我发现自己有一段时间,我可能会真正看到,但我不能答应任何事情。