abstract.py 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. from __future__ import absolute_import
  2. class from_config(object):
  3. def __init__(self, key=None):
  4. self.key = key
  5. def get_key(self, attr):
  6. return attr if self.key is None else self.key
  7. class _configurated(type):
  8. def __new__(cls, name, bases, attrs):
  9. attrs["__confopts__"] = dict((attr, spec.get_key(attr))
  10. for attr, spec in attrs.iteritems()
  11. if isinstance(spec, from_config))
  12. inherit_from = attrs.get("inherit_confopts", ())
  13. for subcls in bases:
  14. try:
  15. attrs["__confopts__"].update(subcls.__confopts__)
  16. except AttributeError:
  17. pass
  18. for subcls in inherit_from:
  19. attrs["__confopts__"].update(subcls.__confopts__)
  20. attrs = dict((k, v if not isinstance(v, from_config) else None)
  21. for k, v in attrs.iteritems())
  22. return super(_configurated, cls).__new__(cls, name, bases, attrs)
  23. class configurated(object):
  24. __metaclass__ = _configurated
  25. def setup_defaults(self, kwargs, namespace="celery"):
  26. confopts = self.__confopts__
  27. app, find = self.app, self.app.conf.find_value_for_key
  28. for attr, keyname in confopts.iteritems():
  29. try:
  30. value = kwargs[attr]
  31. except KeyError:
  32. value = find(keyname, namespace)
  33. else:
  34. if value is None:
  35. value = find(keyname, namespace)
  36. setattr(self, attr, value)
  37. for attr_name, attr_value in kwargs.iteritems():
  38. if attr_name not in confopts and attr_value is not None:
  39. setattr(self, attr_name, attr_value)
  40. def confopts_as_dict(self):
  41. return dict((key, getattr(self, key))
  42. for key in self.__confopts__.iterkeys())