import requests from typing import Type from flask import g class ClientFactory: """Ext API class factory. """ def _get_instance(self, prop_name: str, instance_cls: Type, *args, **kwargs): """Get some object from g or create new. Args: prop_name: G property name. instance_cls: Class to create instance for. """ instance = getattr(g, prop_name, None) if not instance: instance = instance_cls(*args, **kwargs) setattr(g, prop_name, instance) return instance def _get_session(self): """Get session from g or create new. """ return self._get_instance("requests_session", requests.Session) def _get_client(self, client_cls: Type): """Get client from g or create new. """ client_prop_name = f"{client_cls.__name__.lower()}_client" return self._get_instance(client_prop_name, client_cls, self._get_session()) clients = ClientFactory()