Requests does not support asyncio. You can use aiohttp instead, since aiohttp fully supports asyncio and has better performance than requests.
Alternatively, you can use requests with traditional multithreading:
import concurrent.futures import requests def main(): with concurrent.futures.ThreadPoolExecutor() as executor: feature1 = executor.submit(requests.get, 'http://www.google.com') feature2 = executor.submit(requests.get, 'http://www.google.co.uk') print(feature1.result().text) print(feature2.result().text) main()
You can use loop.run_in_executor to integrate executor into asyncio. The above code is semantically equivalent to:
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) asyncio.run(main())
With this approach, you can use any other blocking library with asyncio.
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') print((await future1).text) print((await future2).text) asyncio.run(main())
See PEP 492 for more.
With Python 3.9+, it's even simpler using asyncio.to_thread:
import asyncio import requests async def main(): future1 = asyncio.to_thread(requests.get, 'http://www.google.com') future2 = asyncio.to_thread(requests.get, 'http://www.google.co.uk') print((await future1).text) print((await future2).text) asyncio.run(main())
asyncio.to_thread has another advantage: asyncio.to_thread accepts keyword arguments, while loop.run_in_executor doesn't.
Keep in mind that all of the above code actually uses multithreading under the hood instead of asyncio, so consider using an asynchronous HTTP client such as aiohttp to achieve true asynchrony.
subprocessto parallel your your code.requests(likegoogle-auth) and can't be trivially rewritten to useaiohttp.