diff --git a/app/main.py b/app/main.py index b9aff949..c7e73e99 100644 --- a/app/main.py +++ b/app/main.py @@ -16,13 +16,13 @@ from .config import get_settings from .data import data_source from .routers import V1, V2 -from .utils.httputils import setup_client_session, teardown_client_session +from .utils.httputils import Session # ############ # FastAPI App # ############ LOGGER = logging.getLogger("api") - +session = Session() SETTINGS = get_settings() if SETTINGS.sentry_dsn: # pragma: no cover @@ -37,8 +37,8 @@ version="2.0.4", docs_url="/", redoc_url="/docs", - on_startup=[setup_client_session], - on_shutdown=[teardown_client_session], + on_startup=[session.setup_client_session], + on_shutdown=[session.teardown_client_session], ) # ##################### diff --git a/app/utils/httputils.py b/app/utils/httputils.py index a0793170..7dd13c76 100644 --- a/app/utils/httputils.py +++ b/app/utils/httputils.py @@ -3,28 +3,29 @@ from aiohttp import ClientSession -# Singleton aiohttp.ClientSession instance. -CLIENT_SESSION: ClientSession +class Session: + __CLIENT_SESSION: ClientSession + __LOGGER = logging.getLogger(__name__) + + async def setup_client_session(self) -> None: + """Set up the application-global aiohttp.ClientSession instance. -LOGGER = logging.getLogger(__name__) + aiohttp recommends that only one ClientSession exist for the lifetime of an application. + See: https://docs.aiohttp.org/en/stable/client_quickstart.html#make-a-request + """ + self.__LOGGER.info("Setting up global aiohttp.ClientSession.") + self.__CLIENT_SESSION = ClientSession() + -async def setup_client_session(): - """Set up the application-global aiohttp.ClientSession instance. - aiohttp recommends that only one ClientSession exist for the lifetime of an application. - See: https://docs.aiohttp.org/en/stable/client_quickstart.html#make-a-request + async def teardown_client_session(): + """Close the application-global aiohttp.ClientSession. + """ + self.__LOGGER.info("Closing global aiohttp.ClientSession.") + await self.__CLIENT_SESSION.close() + - """ - global CLIENT_SESSION # pylint: disable=global-statement - LOGGER.info("Setting up global aiohttp.ClientSession.") - CLIENT_SESSION = ClientSession() -async def teardown_client_session(): - """Close the application-global aiohttp.ClientSession. - """ - global CLIENT_SESSION # pylint: disable=global-statement - LOGGER.info("Closing global aiohttp.ClientSession.") - await CLIENT_SESSION.close()