How do I use a long-lived ClientSession? #7570
-
So I need a wrapper class over some REST API, and I want to implement it using aiohttp.
This complicates things a bit. Obviously, I can't just use import asyncio
import typing
import aiohttp
class APIWrapper:
def __init__(self, url: str):
self.url: str = url
self.session: typing.Union[aiohttp.ClientSession, None] = None
async def __aenter__(self) -> 'APIWrapper':
if self.session is None:
self.session = aiohttp.ClientSession()
await self.session.__aenter__()
return self
async def __aexit__(self, exc_type, exc_val, exc_tb):
if self.session is not None:
await self.session.__aexit__(exc_type, exc_val, exc_tb)
self.session = None
async def do_stuff(self) -> typing.Dict[str, typing.Any]:
async with self.session.get(self.url) as resp:
return await resp.json() I then use this code in a relatively simple manner: async def main():
async with APIWrapper('https://dummy.restapiexample.com/api/v1/employee/1') as api:
print(await api.do_stuff())
asyncio.run(main()) And it works, but I get the infamous
|
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 9 replies
-
At a glance, it looks like it should work. I'd just pass through the aenter/aexit methods myself:
If that's a full, working example, I'll try and run it tomorrow. |
Beta Was this translation helpful? Give feedback.
Ah, Windows. Yes, that bug should be fixed in aiohttp 4, which is not released.
However, maybe you should also report a bug to cpython. As you can see in the traceback, aiohttp is nowhere in the traceback, so asyncio is causing the exception, not us: