base.py 4.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137
  1. import os
  2. import re
  3. import sys
  4. import anyjson
  5. from importlib import import_module as _import_module
  6. BUILTIN_MODULES = ["celery.task"]
  7. class BaseLoader(object):
  8. """The base class for loaders.
  9. Loaders handles to following things:
  10. * Reading celery client/worker configurations.
  11. * What happens when a task starts?
  12. See :meth:`on_task_init`.
  13. * What happens when the worker starts?
  14. See :meth:`on_worker_init`.
  15. * What modules are imported to find tasks?
  16. """
  17. _conf_cache = None
  18. worker_initialized = False
  19. override_backends = {}
  20. configured = False
  21. def __init__(self, app=None, **kwargs):
  22. from celery.app import app_or_default
  23. self.app = app_or_default(app)
  24. def on_task_init(self, task_id, task):
  25. """This method is called before a task is executed."""
  26. pass
  27. def on_process_cleanup(self):
  28. """This method is called after a task is executed."""
  29. pass
  30. def on_worker_init(self):
  31. """This method is called when the worker (``celeryd``) starts."""
  32. pass
  33. def import_task_module(self, module):
  34. return self.import_from_cwd(module)
  35. def import_module(self, module):
  36. return _import_module(module)
  37. def import_default_modules(self):
  38. imports = self.conf.get("CELERY_IMPORTS") or []
  39. imports = set(list(imports) + BUILTIN_MODULES)
  40. return map(self.import_task_module, imports)
  41. def init_worker(self):
  42. if not self.worker_initialized:
  43. self.worker_initialized = True
  44. self.on_worker_init()
  45. def cmdline_config_parser(self, args, namespace="celery",
  46. re_type=re.compile(r"\((\w+)\)"),
  47. extra_types={"json": anyjson.deserialize},
  48. override_types={"tuple": "json",
  49. "list": "json",
  50. "dict": "json"}):
  51. from celery.app.defaults import Option, NAMESPACES
  52. namespace = namespace.upper()
  53. typemap = dict(Option.typemap, **extra_types)
  54. def getarg(arg):
  55. """Parse a single configuration definition from
  56. the command line."""
  57. ## find key/value
  58. # ns.key=value|ns_key=value (case insensitive)
  59. key, value = arg.replace('.', '_').split('=', 1)
  60. key = key.upper()
  61. ## find namespace.
  62. # .key=value|_key=value expands to default namespace.
  63. if key[0] == '_':
  64. ns, key = namespace, key[1:]
  65. else:
  66. # find namespace part of key
  67. ns, key = key.split('_', 1)
  68. ns_key = (ns and ns + "_" or "") + key
  69. # (type)value makes cast to custom type.
  70. cast = re_type.match(value)
  71. if cast:
  72. type_ = cast.groups()[0]
  73. type_ = override_types.get(type_, type_)
  74. value = value[len(cast.group()):]
  75. value = typemap[type_](value)
  76. else:
  77. try:
  78. value = NAMESPACES[ns][key].to_python(value)
  79. except ValueError, exc:
  80. # display key name in error message.
  81. raise ValueError("%r: %s" % (ns_key, exc))
  82. return ns_key, value
  83. return dict(map(getarg, args))
  84. def import_from_cwd(self, module, imp=None):
  85. """Import module, but make sure it finds modules
  86. located in the current directory.
  87. Modules located in the current directory has
  88. precedence over modules located in ``sys.path``.
  89. """
  90. if imp is None:
  91. imp = self.import_module
  92. cwd = os.getcwd()
  93. if cwd in sys.path:
  94. return imp(module)
  95. sys.path.insert(0, cwd)
  96. try:
  97. return imp(module)
  98. finally:
  99. try:
  100. sys.path.remove(cwd)
  101. except ValueError:
  102. pass
  103. @property
  104. def conf(self):
  105. """Loader configuration."""
  106. if not self._conf_cache:
  107. self._conf_cache = self.read_configuration()
  108. return self._conf_cache