Development of an internal social media platform with personalised dashboards for students
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

annotations.py 1.5KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. # -*- coding: utf-8 -*-
  2. """
  3. celery.app.annotations
  4. ~~~~~~~~~~~~~~~~~~~~~~
  5. Annotations is a nice term for monkey patching
  6. task classes in the configuration.
  7. This prepares and performs the annotations in the
  8. :setting:`CELERY_ANNOTATIONS` setting.
  9. """
  10. from __future__ import absolute_import
  11. from celery.five import string_t
  12. from celery.utils.functional import firstmethod, mlazy
  13. from celery.utils.imports import instantiate
  14. _first_match = firstmethod('annotate')
  15. _first_match_any = firstmethod('annotate_any')
  16. __all__ = ['MapAnnotation', 'prepare', 'resolve_all']
  17. class MapAnnotation(dict):
  18. def annotate_any(self):
  19. try:
  20. return dict(self['*'])
  21. except KeyError:
  22. pass
  23. def annotate(self, task):
  24. try:
  25. return dict(self[task.name])
  26. except KeyError:
  27. pass
  28. def prepare(annotations):
  29. """Expands the :setting:`CELERY_ANNOTATIONS` setting."""
  30. def expand_annotation(annotation):
  31. if isinstance(annotation, dict):
  32. return MapAnnotation(annotation)
  33. elif isinstance(annotation, string_t):
  34. return mlazy(instantiate, annotation)
  35. return annotation
  36. if annotations is None:
  37. return ()
  38. elif not isinstance(annotations, (list, tuple)):
  39. annotations = (annotations, )
  40. return [expand_annotation(anno) for anno in annotations]
  41. def resolve_all(anno, task):
  42. return (x for x in (_first_match(anno, task), _first_match_any(anno)) if x)