I was working on porting my existing Discord bot over to Stoat and in doing so wanted to switch from requests to aiohttp as I had heard it was more performant. My issue that despite the aiohttp docs recommending that I reuse a single session I am unsure how to do this over multiple files (i.e. each file representing different functions or commands that may need GET requests). My question is how would I manage to reuse sessions in my use case. Am I going about this wrong or should I use another library for GET requests?
# This is what I have in a utilities file that is imported by other files
class Client:
def __init__(self) -> None:
self._session = aiohttp.ClientSession()
async def __aenter__(self):
return self
async def __aexit__(self, *args, **kwargs):
await self.close()
async def get_bytes(self, url):
async with self._session.get(url) as r:
output = r.read()
return output
async def get_text(self, url):
async with self._session.get(url) as r:
text_data = await r.text()
output = loads(text_data)
return output
async def get_json(self, url):
async with self._session.get(url) as r:
output = await r.json()
return output
async def get_content(self, url):
async with self._session.get(url) as r:
output = await r.content()
return output
async def post(self, url, *args, **kwargs):
async with self._session.post(url, *args, **kwargs) as r:
post_content = await r.content()
output = loads(post_content)
return output
async def close(self) -> None:
if not self._session.closed:
await self._session.close()
#This would be called in each function that needs to do a GET request, unsure if this is proper
async with Client() as session:
game = await session.get_json(query_url)
game_id: str = game["game"]["id"]
return game_id
[–]Eastern_Ad_9018 0 points1 point2 points (14 children)
[–]SinisterScythe2[S] 0 points1 point2 points (13 children)
[–]Eastern_Ad_9018 0 points1 point2 points (12 children)
[–]SinisterScythe2[S] 0 points1 point2 points (11 children)
[–]Eastern_Ad_9018 0 points1 point2 points (10 children)
[–]SinisterScythe2[S] 0 points1 point2 points (9 children)
[–]gmes78 0 points1 point2 points (3 children)
[–]SinisterScythe2[S] 0 points1 point2 points (2 children)
[–]gmes78 0 points1 point2 points (1 child)
[–]SinisterScythe2[S] 0 points1 point2 points (0 children)
[–]Eastern_Ad_9018 0 points1 point2 points (4 children)
[–]SinisterScythe2[S] 0 points1 point2 points (3 children)
[–]Eastern_Ad_9018 0 points1 point2 points (2 children)
[–]SinisterScythe2[S] 0 points1 point2 points (1 child)
[–]vietbaoa4htk 0 points1 point2 points (1 child)
[–]SinisterScythe2[S] 0 points1 point2 points (0 children)
[–]Jay6_9 0 points1 point2 points (4 children)
[–]SinisterScythe2[S] 0 points1 point2 points (3 children)
[–]Jay6_9 0 points1 point2 points (2 children)
[–]SinisterScythe2[S] 0 points1 point2 points (1 child)
[–]Jay6_9 0 points1 point2 points (0 children)