registries.py 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  1. # Copyright © 2023 Ingram Micro Inc. All rights reserved.
  2. import logging
  3. from django.conf import settings
  4. logger = logging.getLogger('django-cqrs')
  5. class RegistryMixin:
  6. @classmethod
  7. def register_model(cls, model_cls):
  8. """Registration of CQRS model identifiers."""
  9. e = "Two models can't have the same CQRS_ID: {0}.".format(model_cls.CQRS_ID)
  10. assert model_cls.CQRS_ID not in cls.models, e
  11. cls.models[model_cls.CQRS_ID] = model_cls
  12. @classmethod
  13. def get_model_by_cqrs_id(cls, cqrs_id):
  14. """
  15. Returns the model class given its CQRS_ID.
  16. Args:
  17. cqrs_id (str): The CQRS_ID of the model to be retrieved.
  18. Returns:
  19. (django.db.models.Model): The model that correspond to the given CQRS_ID or None if it
  20. has not been registered.
  21. """
  22. if cqrs_id in cls.models:
  23. return cls.models[cqrs_id]
  24. logger.error('No model with such CQRS_ID: {0}.'.format(cqrs_id))
  25. class MasterRegistry(RegistryMixin):
  26. models = {}
  27. class ReplicaRegistry(RegistryMixin):
  28. models = {}
  29. @classmethod
  30. def register_model(cls, model_cls):
  31. e = 'CQRS queue must be set for the service, that has replica models.'
  32. assert getattr(settings, 'CQRS', {}).get('queue') is not None, e
  33. super(ReplicaRegistry, cls).register_model(model_cls)