_state.py 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293
  1. # -*- coding: utf-8 -*-
  2. """
  3. celery._state
  4. ~~~~~~~~~~~~~~~
  5. This is an internal module containing thread state
  6. like the ``current_app``, and ``current_task``.
  7. This module shouldn't be used directly.
  8. """
  9. from __future__ import absolute_import
  10. import os
  11. import threading
  12. import weakref
  13. from celery.local import Proxy
  14. from celery.utils.threads import LocalStack
  15. #: Global default app used when no current app.
  16. default_app = None
  17. #: List of all app instances (weakrefs), must not be used directly.
  18. _apps = set()
  19. class _TLS(threading.local):
  20. #: Apps with the :attr:`~celery.app.base.BaseApp.set_as_current` attribute
  21. #: sets this, so it will always contain the last instantiated app,
  22. #: and is the default app returned by :func:`app_or_default`.
  23. current_app = None
  24. _tls = _TLS()
  25. _task_stack = LocalStack()
  26. def set_default_app(app):
  27. global default_app
  28. default_app = app
  29. def get_current_app():
  30. if default_app is None:
  31. #: creates the global fallback app instance.
  32. from celery.app import Celery
  33. set_default_app(Celery('default',
  34. loader=os.environ.get('CELERY_LOADER') or 'default',
  35. set_as_current=False, accept_magic_kwargs=True))
  36. return _tls.current_app or default_app
  37. def get_current_task():
  38. """Currently executing task."""
  39. return _task_stack.top
  40. def get_current_worker_task():
  41. """Currently executing task, that was applied by the worker.
  42. This is used to differentiate between the actual task
  43. executed by the worker and any task that was called within
  44. a task (using ``task.__call__`` or ``task.apply``)
  45. """
  46. for task in reversed(_task_stack.stack):
  47. if not task.request.called_directly:
  48. return task
  49. #: Proxy to current app.
  50. current_app = Proxy(get_current_app)
  51. #: Proxy to current task.
  52. current_task = Proxy(get_current_task)
  53. def _register_app(app):
  54. _apps.add(weakref.ref(app))
  55. def _get_active_apps():
  56. dirty = []
  57. try:
  58. for appref in _apps:
  59. app = appref()
  60. if app is None:
  61. dirty.append(appref)
  62. else:
  63. yield app
  64. finally:
  65. while dirty:
  66. _apps.discard(dirty.pop())