default.py 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. import os
  2. import warnings
  3. from importlib import import_module
  4. from celery.loaders.base import BaseLoader
  5. from celery.datastructures import AttributeDict
  6. from celery.exceptions import NotConfigured
  7. DEFAULT_CONFIG_MODULE = "celeryconfig"
  8. DEFAULT_SETTINGS = {
  9. "DEBUG": False,
  10. "ADMINS": (),
  11. "DATABASE_ENGINE": "sqlite3",
  12. "DATABASE_NAME": "celery.sqlite",
  13. "INSTALLED_APPS": ("celery", ),
  14. "CELERY_IMPORTS": (),
  15. "CELERY_TASK_ERROR_WHITELIST": (),
  16. }
  17. DEFAULT_UNCONFIGURED_SETTINGS = {
  18. "CELERY_RESULT_BACKEND": "amqp",
  19. }
  20. def wanted_module_item(item):
  21. return not item.startswith("_")
  22. class Loader(BaseLoader):
  23. """The default loader.
  24. See the FAQ for example usage.
  25. """
  26. def setup_settings(self, settingsdict):
  27. settings = AttributeDict(DEFAULT_SETTINGS, **settingsdict)
  28. installed_apps = set(list(DEFAULT_SETTINGS["INSTALLED_APPS"]) + \
  29. list(settings.INSTALLED_APPS))
  30. settings.INSTALLED_APPS = tuple(installed_apps)
  31. settings.CELERY_TASK_ERROR_WHITELIST = tuple(
  32. getattr(import_module(mod), cls)
  33. for fqn in settings.CELERY_TASK_ERROR_WHITELIST
  34. for mod, cls in (fqn.rsplit('.', 1), ))
  35. return settings
  36. def read_configuration(self):
  37. """Read configuration from ``celeryconfig.py`` and configure
  38. celery and Django so it can be used by regular Python."""
  39. configname = os.environ.get("CELERY_CONFIG_MODULE",
  40. DEFAULT_CONFIG_MODULE)
  41. try:
  42. celeryconfig = self.import_from_cwd(configname)
  43. except ImportError:
  44. warnings.warn("No celeryconfig.py module found! Please make "
  45. "sure it exists and is available to Python.",
  46. NotConfigured)
  47. return self.setup_settings(DEFAULT_UNCONFIGURED_SETTINGS)
  48. else:
  49. usercfg = dict((key, getattr(celeryconfig, key))
  50. for key in dir(celeryconfig)
  51. if wanted_module_item(key))
  52. self.configured = True
  53. return self.setup_settings(usercfg)
  54. def on_worker_init(self):
  55. """Imports modules at worker init so tasks can be registered
  56. and used by the worked.
  57. The list of modules to import is taken from the
  58. :setting:`CELERY_IMPORTS` setting.
  59. """
  60. self.import_default_modules()