Cleanly close aiohttp session on exit

This commit is contained in:
Adam Goldsmith 2021-05-02 23:40:57 -04:00
parent add2e0362a
commit 727476112e

View File

@ -1,3 +1,4 @@
import asyncio
from typing import Any from typing import Any
import aiohttp import aiohttp
@ -8,19 +9,27 @@ ArkhamDBDeck = Any # TODO: better typing
class ArkhamDBClient: class ArkhamDBClient:
session: aiohttp.ClientSession _session: aiohttp.ClientSession
origin: str origin: str
def __init__(self, arkhamdb_origin: str = ARKHAMDB_ORIGIN): def __init__(self, arkhamdb_origin: str = ARKHAMDB_ORIGIN):
self.session = aiohttp.ClientSession() self._session = aiohttp.ClientSession()
self.origin = arkhamdb_origin self.origin = arkhamdb_origin
def __del__(self):
loop = asyncio.get_event_loop()
loop.run_until_complete(self.close())
async def close(self):
await self._session.close()
async def get_latest_deck(self, deck_id: int) -> ArkhamDBDeck: async def get_latest_deck(self, deck_id: int) -> ArkhamDBDeck:
next_deck_id = deck_id next_deck_id = deck_id
deck = None deck = None
while deck is None or deck["next_deck"] is not None: while deck is None or deck["next_deck"] is not None:
async with self.session.get(self.origin + f"/api/public/deck/{next_deck_id}.json") as resp: async with self._session.get(
self.origin + f"/api/public/deck/{next_deck_id}.json") as resp:
deck = await resp.json() deck = await resp.json()
next_deck_id = deck["next_deck"] next_deck_id = deck["next_deck"]