djangoapp.py 2.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  1. import imp
  2. import importlib
  3. from celery.loaders.base import BaseLoader
  4. _RACE_PROTECTION = False
  5. class Loader(BaseLoader):
  6. """The Django loader."""
  7. def read_configuration(self):
  8. """Load configuration from Django settings."""
  9. from django.conf import settings
  10. return settings
  11. def on_task_init(self, task_id, task):
  12. """This method is called before a task is executed.
  13. Does everything necessary for Django to work in a long-living,
  14. multiprocessing environment.
  15. """
  16. # See: http://groups.google.com/group/django-users/browse_thread/
  17. # thread/78200863d0c07c6d/38402e76cf3233e8?hl=en&lnk=gst&
  18. # q=multiprocessing#38402e76cf3233e8
  19. from django.db import connection
  20. connection.close()
  21. # ## Reset cache connection only if using memcached/libmemcached
  22. from django.core import cache
  23. # XXX At Opera we use a custom memcached backend that uses
  24. # libmemcached instead of libmemcache (cmemcache). Should find a
  25. # better solution for this, but for now "memcached" should probably
  26. # be unique enough of a string to not make problems.
  27. cache_backend = cache.settings.CACHE_BACKEND
  28. try:
  29. parse_backend = cache.parse_backend_uri
  30. except AttributeError:
  31. parse_backend = lambda backend: backend.split(":", 1)
  32. cache_scheme = parse_backend(cache_backend)[0]
  33. if "memcached" in cache_scheme:
  34. cache.cache.close()
  35. def on_worker_init(self):
  36. """Called when the worker starts.
  37. Automatically discovers any ``tasks.py`` files in the applications
  38. listed in ``INSTALLED_APPS``.
  39. """
  40. self.import_default_modules()
  41. autodiscover()
  42. def autodiscover():
  43. """Include tasks for all applications in :setting:`INSTALLED_APPS`."""
  44. from django.conf import settings
  45. global _RACE_PROTECTION
  46. if _RACE_PROTECTION:
  47. return
  48. _RACE_PROTECTION = True
  49. try:
  50. return filter(None, [find_related_module(app, "tasks")
  51. for app in settings.INSTALLED_APPS])
  52. finally:
  53. _RACE_PROTECTION = False
  54. def find_related_module(app, related_name):
  55. """Given an application name and a module name, tries to find that
  56. module in the application."""
  57. try:
  58. app_path = importlib.import_module(app).__path__
  59. except AttributeError:
  60. return
  61. try:
  62. imp.find_module(related_name, app_path)
  63. except ImportError:
  64. return
  65. module = importlib.import_module("%s.%s" % (app, related_name))
  66. try:
  67. return getattr(module, related_name)
  68. except AttributeError:
  69. return