Sunday, 27 December 2020

Is there an essential difference between await and async-with while doing request in aiohttp?

My question is about the right way to making response in aiohttp

Official aiohttp documentation gives us the example of making an async query:

session = aiohttp.ClientSession()

async with session.get('http://httpbin.org/get') as resp:
    print(resp.status)
    print(await resp.text())

await session.close()

I cannot understand, why is the context manager here. All i have found is that __aexit__() method awaits resp.release() method. But the documentation also tells that awaiting resp.release() is not necessary at general.

That all really confuses me.

Why should i do that way if i find the code below more readable and not so nested?

session = aiohttp.ClientSession()

resp = await session.get('http://httpbin.org/get')
print(resp.status)
print(await resp.text())

# I finally have not get the essence of this method.
# I've tried both using and not using this method in my code,
# I've not found any difference in behaviour.
# await resp.release()

await session.close()

I have dug into aiohttp.ClientSession and its context manager sources, but i have not found anything that could clarify the situation.

In the end, my question: what's the difference?



from Is there an essential difference between await and async-with while doing request in aiohttp?

No comments:

Post a Comment