How to use only one session for all the lifecycle of my application with Aiohttp?

Viewed 393

I'm making a python module for interacting with an API. I'd like it to be fast, so I chose to use asyncio and Aiohttp. I'm quite new to async programming and I'm not quite sure how to reuse the same session for every request. Also, I'd like to spare my end-users the hassle of creating the loop etc. I came up with this class for my base client:

import asyncio
import aiohttp


class BaseClient:
    API_BASE_URL = "dummyURL"
    API_VERSION = 3

    async def __aenter__(self):
        self._session = aiohttp.ClientSession(raise_for_status=True)
        return self

    async def __aexit__(self, exc_type, exc, tb):
        await self._session.close()
        #remove the next line when aiohttp 4.0 is released
        await asyncio.sleep(0.250)

    async def _get(self, endpoint: str) -> None:
        url = f"{self.API_BASE_URL}/{endpoint}/?v={self.API_VERSION}"
        async with self._session.get(url) as resp:
            json_body = await resp.json()
            return json_body

    async def list_forums(self):
        endpoint = "forums"
        return await self._get(endpoint)


async def main():
    async with BaseClient() as client:
        forums = await client.list_forums()
        print(forums)


asyncio.run(main())

Is that the right way to reuse the same session? Is it possible to refactor BaseClient in such a way my end-users would only have to dothe following:

client = BaseClient()
forums = client.list_forums()

Thanks for your help.

0 Answers
Related