app.py 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. import os
  2. import sys
  3. from importlib import import_module
  4. from celery.datastructures import DictAttribute
  5. from celery.exceptions import ImproperlyConfigured
  6. from celery.loaders.base import BaseLoader
  7. ERROR_ENVVAR_NOT_SET = (
  8. """The environment variable %r is not set,
  9. and as such the configuration could not be loaded.
  10. Please set this variable and make it point to
  11. a configuration module.""")
  12. class AppLoader(BaseLoader):
  13. def __init__(self, *args, **kwargs):
  14. self._conf = {}
  15. super(AppLoader, self).__init__(*args, **kwargs)
  16. def config_from_envvar(self, variable_name, silent=False):
  17. module_name = os.environ.get(variable_name)
  18. if not module_name:
  19. if silent:
  20. return False
  21. raise ImproperlyConfigured(ERROR_ENVVAR_NOT_SET % (module_name, ))
  22. return self.config_from_object(module_name, silent=silent)
  23. def config_from_object(self, obj, silent=False):
  24. if isinstance(obj, basestring):
  25. try:
  26. obj = self.import_from_cwd(obj)
  27. except ImportError:
  28. if silent:
  29. return False
  30. raise
  31. if not hasattr(obj, "__getitem__"):
  32. obj = DictAttribute(obj)
  33. self._conf = obj
  34. return True
  35. def on_worker_init(self):
  36. self.import_default_modules()
  37. def import_from_cwd(self, module, imp=import_module):
  38. """Import module, but make sure it finds modules
  39. located in the current directory.
  40. Modules located in the current directory has
  41. precedence over modules located in ``sys.path``.
  42. """
  43. cwd = os.getcwd()
  44. if cwd in sys.path:
  45. return imp(module)
  46. sys.path.insert(0, cwd)
  47. try:
  48. return imp(module)
  49. finally:
  50. try:
  51. sys.path.remove(cwd)
  52. except ValueError:
  53. pass
  54. @property
  55. def conf(self):
  56. return self._conf