We know we can do a lot of async stuff with asyncio but have you ever wondered how to execute blocking codes with it? It’s pretty simple actually, asyncio allows us to run blocking code using BaseEventLoop.run_in_executor method. It will run our functions in parallel and provide us with Future objects which we can await or yield from.
Let’s see an example with the popular requests library:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
import asyncio import requests loop = asyncio.get_event_loop() def get_html(url): return loop.run_in_executor(None, requests.get, url) @asyncio.coroutine def main(): resp1 = yield from get_html("https://masnun.com") resp2 = yield from get_html("http://python.org") print(resp2, resp1) loop.run_until_complete(main()) |
If you run the code snippet, you can see how the two responses are fetched asynchronously 🙂