Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why aiohttp deprecated the loop parameter in ClientSession?

Tags:

python

aiohttp

In the aiohttp's doc reads:

  • loop – event loop used for processing HTTP requests. If loop is None the constructor borrows it from connector if specified. asyncio.get_event_loop() is used for getting default event loop otherwise.

Deprecated since version 2.0.

I googled but didn't get any description about why the loop parameter is deprecated.

I often create ClientSession object like this:

loop = asyncio.get_event_loop()
session = aiohttp.ClientSession(loop=loop)

Now the loop parameter is depracted, but just call aiohttp.ClientSession() without the loop will get a warning:

Creating a client session outside of coroutine

So why the parameter is deprecated and how to use the session correctly?

like image 950
CSM Avatar asked Jan 06 '18 06:01

CSM


1 Answers

This question is addressed in this issue which is advising that the client session object be created within a coroutine to avoid errors that are difficult to debug. The preferred usage is demonstrated here; for reference:

async def fetch(client):
    async with client.get('http://python.org') as resp:
        assert resp.status == 200
        return await resp.text()

async def main():
    async with aiohttp.ClientSession() as client:
        html = await fetch(client)
        print(html)

loop = asyncio.get_event_loop()
loop.run_until_complete(main())
like image 133
Ben Avatar answered Oct 26 '22 16:10

Ben