如何在asyncio中使用请求? [英] How could I use requests in asyncio?
问题描述
我想在 asyncio
中执行并行http请求任务,但是我发现 python-requests
会阻止 asyncio
的事件循环。我发现 aiohttp ,但是它无法使用http代理提供http请求服务。
所以我想知道是否有一种方法可以借助 asyncio
进行异步http请求。
要将请求(或任何其他阻止库)与asyncio一起使用,可以使用 BaseEventLoop.run_in_executor 可以在另一个线程中运行一个函数,并从另一个线程中屈服以获得结果。例如:
导入asyncio
导入请求
@ asyncio.coroutine
def main():
loop = asyncio.get_event_loop()
future1 = loop.run_in_executor(无,requests.get, http://www.google.com)
future2 = loop.run_in_executor(无,requests.get,'http://www.google.co.uk')
响应1 =未来1的收益
响应2 =未来2的收益
print(response1 .text)
print(response2.text)
loop = asyncio.get_event_loop()
loop.run_until_complete(main())
这将同时获得两个响应。
使用python 3.5,您可以使用新的等待
/ 异步
语法:
导入异步
导入请求
异步def main():
loop = asyncio.get_event_loop()
future1 = loop.run_in_executor(无, requests.get,'http://www.google.com')
future2 = loop.run_in_executor(无,重新quests.get,'http://www.google.co.uk')
response1 =等待未来1
response2 =等待未来2
print(response1.text)
print( response2.text)
loop = asyncio.get_event_loop()
loop.run_until_complete(main())
有关更多信息,请参见 PEP0492 。 / p>
I want to do parallel http request tasks in asyncio
, but I find that python-requests
would block the event loop of asyncio
. I've found aiohttp but it couldn't provide the service of http request using a http proxy.
So I want to know if there's a way to do asynchronous http requests with the help of asyncio
.
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.
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())
See PEP0492 for more.
这篇关于如何在asyncio中使用请求?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!