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
.
The answers above are still using the old Python 3.4 style coroutines. Here is what you would write if you got Python 3.5+.
aiohttp
supports http proxy nowaiohttp can be used with HTTP proxy already:
Requests does not currently support
asyncio
and there are no plans to provide such support. It's likely that you could implement a custom "Transport Adapter" (as discussed here) that knows how to useasyncio
.If I find myself with some time it's something I might actually look into, but I can't promise anything.
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:
This will get both responses in parallel.
With python 3.5 you can use the new
await
/async
syntax:See PEP0492 for more.
There is a good case of async/await loops and threading in an article by Pimin Konstantin Kefaloukos Easy parallel HTTP requests with Python and asyncio: