Asyncio requests

Hello. I currently have a small application:


Now I have a problem with requests.get (...).
I want the request to be sent asynchronously (asyncio), for example like this:

response_generator = await requests.get(settings.GENERATOR_HOST)
return response.html(response_generator.content)

But how do I do? I know that this can be easily done by aiohttp (but it will be easier to switch to the aiohttp framework than installing it).

Hello, @Max! Welcome to our forums and thanks for choosing Sanic!

So, your question might be fairly simple to solve, but it might not be very, well, easy. The one thing that you want is actually not supported by the requests library, since it does not have support for asyncio (it has support for asynchronous operations, but not wrapped to use await). You’ll either:

  1. have to wrap it yourself to make it async;
  2. Use aiohttp, that has a nice, fully async http client :wink:

You can read more about switching from synchronous requests to asynchronous aiohttp in this article.

Hope this helps!

2 Likes