djangoapp.py 2.6 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/
  17. # browse_thread/thread/78200863d0c07c6d/
  18. from django.db import connection
  19. connection.close()
  20. # ## Reset cache connection only if using memcached/libmemcached
  21. from django.core import cache
  22. # XXX At Opera we use a custom memcached backend that uses
  23. # libmemcached instead of libmemcache (cmemcache). Should find a
  24. # better solution for this, but for now "memcached" should probably
  25. # be unique enough of a string to not make problems.
  26. cache_backend = cache.settings.CACHE_BACKEND
  27. try:
  28. parse_backend = cache.parse_backend_uri
  29. except AttributeError:
  30. parse_backend = lambda backend: backend.split(":", 1)
  31. cache_scheme = parse_backend(cache_backend)[0]
  32. if "memcached" in cache_scheme:
  33. cache.cache.close()
  34. def on_worker_init(self):
  35. """Called when the worker starts.
  36. Automatically discovers any ``tasks.py`` files in the applications
  37. listed in ``INSTALLED_APPS``.
  38. """
  39. self.import_default_modules()
  40. autodiscover()
  41. def autodiscover():
  42. """Include tasks for all applications in :setting:`INSTALLED_APPS`."""
  43. from django.conf import settings
  44. global _RACE_PROTECTION
  45. if _RACE_PROTECTION:
  46. return
  47. _RACE_PROTECTION = True
  48. try:
  49. return filter(None, [find_related_module(app, "tasks")
  50. for app in settings.INSTALLED_APPS])
  51. finally:
  52. _RACE_PROTECTION = False
  53. def find_related_module(app, related_name):
  54. """Given an application name and a module name, tries to find that
  55. module in the application."""
  56. try:
  57. app_path = importlib.import_module(app).__path__
  58. except AttributeError:
  59. return
  60. try:
  61. imp.find_module(related_name, app_path)
  62. except ImportError:
  63. return
  64. module = importlib.import_module("%s.%s" % (app, related_name))
  65. try:
  66. return getattr(module, related_name)
  67. except AttributeError:
  68. return