diff --git a/app/data/__init__.py b/app/data/__init__.py index 393ea55c..455a0ce0 100644 --- a/app/data/__init__.py +++ b/app/data/__init__.py @@ -2,9 +2,10 @@ from ..services.location.csbs import CSBSLocationService from ..services.location.jhu import JhuLocationService from ..services.location.nyt import NYTLocationService +from ..utils.singleton import Singleton -class DataSources: +class DataSources(Singleton): """ Class to represent the root of the aggregate containing the location services. """ @@ -16,9 +17,16 @@ class DataSources: "nyt": NYTLocationService(), } + __instance = None + def __init__(self): pass + def get_instance(): + if DataSources.__instance is None: + DataSources.__instance = DataSources() + return DataSources.__instance + def get_data_source(self, source): """ Retrieves the provided data-source service. diff --git a/app/main.py b/app/main.py index 77a488ff..d6b480e2 100644 --- a/app/main.py +++ b/app/main.py @@ -41,7 +41,7 @@ on_shutdown=[teardown_client_session], ) -DATA_SOURCES = DataSources() +DATA_SOURCES = DataSources.get_instance() # ##################### # Middleware diff --git a/app/routers/v2.py b/app/routers/v2.py index e1649151..96cdd67d 100644 --- a/app/routers/v2.py +++ b/app/routers/v2.py @@ -7,7 +7,7 @@ from ..models import LatestResponse, LocationResponse, LocationsResponse V2 = APIRouter() -DATA_SOURCES = DataSources() +DATA_SOURCES = DataSources.get_instance() class Sources(str, enum.Enum): diff --git a/app/utils/singleton.py b/app/utils/singleton.py new file mode 100644 index 00000000..501e4fbd --- /dev/null +++ b/app/utils/singleton.py @@ -0,0 +1,11 @@ +class Singleton(object): + def __new__(cls, *args, **kwds): + it = cls.__dict__.get("__it__") + if it is not None: + return it + cls.__it__ = it = object.__new__(cls) + it.init(*args, **kwds) + return it + + def init(self, *args, **kwds): + pass