I am writing a tool in Python 3.6 that sends requests to several APIs (with various endpoints) and collects their responses to parse and save them in a database.
The API clients that I use have a synchronous version of requesting a URL, for instance they use
urllib.request.Request('...
Or they use Kenneth Reitz' Requests
library.
Since my API calls rely on synchronous versions of requesting a URL, the whole process takes several minutes to complete.
Now I'd like to wrap my API calls in async/await (asyncio). I'm using python 3.6.
All the examples / tutorials that I found want me to change the synchronous URL calls / requests
to an async version of it (for instance aiohttp
). Since my code relies on API clients that I haven't written (and I can't change) I need to leave that code untouched.
So is there a way to wrap my synchronous requests (blocking code) in async/await to make them run in an event loop?
I'm new to asyncio in Python. This would be a no-brainer in NodeJS. But I can't wrap my head around this in Python.
Update 2023-06-12
Here's how I'd do it in Python 3.9+
import asyncio
import requests
async def main():
response1 = await asyncio.to_thread(requests.get, 'http://httpbin.org/get')
response2 = await asyncio.to_thread(requests.get, 'https://api.github.com/events')
print(response1.text)
print(response2.text)
asyncio.run(main())