default.py 2.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  1. # -*- coding: utf-8 -*-
  2. """
  3. celery.loaders.default
  4. ~~~~~~~~~~~~~~~~~~~~~~
  5. The default loader used when no custom app has been initialized.
  6. :copyright: (c) 2009 - 2012 by Ask Solem.
  7. :license: BSD, see LICENSE for more details.
  8. """
  9. from __future__ import absolute_import
  10. import os
  11. import sys
  12. import warnings
  13. from ..datastructures import AttributeDict
  14. from ..exceptions import NotConfigured
  15. from ..utils import find_module, NotAPackage
  16. from .base import BaseLoader
  17. DEFAULT_CONFIG_MODULE = "celeryconfig"
  18. CONFIG_INVALID_NAME = """
  19. Error: Module '%(module)s' doesn't exist, or it's not a valid \
  20. Python module name.
  21. """
  22. CONFIG_WITH_SUFFIX = CONFIG_INVALID_NAME + """
  23. Did you mean '%(suggest)s'?
  24. """
  25. class Loader(BaseLoader):
  26. """The loader used by the default app."""
  27. def setup_settings(self, settingsdict):
  28. return AttributeDict(settingsdict)
  29. def find_module(self, module):
  30. return find_module(module)
  31. def read_configuration(self):
  32. """Read configuration from :file:`celeryconfig.py` and configure
  33. celery and Django so it can be used by regular Python."""
  34. configname = os.environ.get("CELERY_CONFIG_MODULE",
  35. DEFAULT_CONFIG_MODULE)
  36. try:
  37. self.find_module(configname)
  38. except NotAPackage:
  39. if configname.endswith('.py'):
  40. raise NotAPackage, NotAPackage(
  41. CONFIG_WITH_SUFFIX % {
  42. "module": configname,
  43. "suggest": configname[:-3]}), sys.exc_info()[2]
  44. raise NotAPackage, NotAPackage(
  45. CONFIG_INVALID_NAME % {
  46. "module": configname}), sys.exc_info()[2]
  47. except ImportError:
  48. warnings.warn(NotConfigured(
  49. "No %r module found! Please make sure it exists and "
  50. "is available to Python." % (configname, )))
  51. return self.setup_settings({})
  52. else:
  53. celeryconfig = self.import_from_cwd(configname)
  54. usercfg = dict((key, getattr(celeryconfig, key))
  55. for key in dir(celeryconfig)
  56. if self.wanted_module_item(key))
  57. self.configured = True
  58. return self.setup_settings(usercfg)
  59. def wanted_module_item(self, item):
  60. return item[0].isupper() and not item.startswith("_")
  61. def on_worker_init(self):
  62. """Imports modules at worker init so tasks can be registered
  63. and used by the worked.
  64. The list of modules to import is taken from the
  65. :setting:`CELERY_IMPORTS` setting.
  66. """
  67. self.import_default_modules()