__init__.py 7.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194
  1. from celery import conf
  2. from celery.datastructures import ExceptionInfo
  3. from celery.execute.trace import TaskTrace
  4. from celery.messaging import with_connection
  5. from celery.messaging import TaskPublisher
  6. from celery.registry import tasks
  7. from celery.result import AsyncResult, EagerResult
  8. from celery.routes import Router
  9. from celery.utils import gen_unique_id, fun_takes_kwargs, mattrgetter
  10. extract_exec_options = mattrgetter("queue", "routing_key", "exchange",
  11. "immediate", "mandatory",
  12. "priority", "serializer",
  13. "delivery_mode")
  14. @with_connection
  15. def apply_async(task, args=None, kwargs=None, countdown=None, eta=None,
  16. task_id=None, publisher=None, connection=None, connect_timeout=None,
  17. router=None, **options):
  18. """Run a task asynchronously by the celery daemon(s).
  19. :param task: The :class:`~celery.task.base.Task` to run.
  20. :keyword args: The positional arguments to pass on to the
  21. task (a :class:`list` or :class:`tuple`).
  22. :keyword kwargs: The keyword arguments to pass on to the
  23. task (a :class:`dict`)
  24. :keyword countdown: Number of seconds into the future that the task should
  25. execute. Defaults to immediate delivery (Do not confuse that with
  26. the ``immediate`` setting, they are unrelated).
  27. :keyword eta: A :class:`~datetime.datetime` object that describes the
  28. absolute time when the task should execute. May not be specified
  29. if ``countdown`` is also supplied. (Do not confuse this with the
  30. ``immediate`` setting, they are unrelated).
  31. :keyword connection: Re-use existing broker connection instead
  32. of establishing a new one. The ``connect_timeout`` argument is
  33. not respected if this is set.
  34. :keyword connect_timeout: The timeout in seconds, before we give up
  35. on establishing a connection to the AMQP server.
  36. :keyword routing_key: The routing key used to route the task to a worker
  37. server. Defaults to the tasks :attr:`~celery.task.base.Task.exchange`
  38. attribute.
  39. :keyword exchange: The named exchange to send the task to. Defaults to
  40. the tasks :attr:`~celery.task.base.Task.exchange` attribute.
  41. :keyword exchange_type: The exchange type to initalize the exchange as
  42. if not already declared. Defaults to the tasks
  43. :attr:`~celery.task.base.Task.exchange_type` attribute.
  44. :keyword immediate: Request immediate delivery. Will raise an exception
  45. if the task cannot be routed to a worker immediately.
  46. (Do not confuse this parameter with the ``countdown`` and ``eta``
  47. settings, as they are unrelated). Defaults to the tasks
  48. :attr:`~celery.task.base.Task.immediate` attribute.
  49. :keyword mandatory: Mandatory routing. Raises an exception if there's
  50. no running workers able to take on this task. Defaults to the tasks
  51. :attr:`~celery.task.base.Task.mandatory` attribute.
  52. :keyword priority: The task priority, a number between ``0`` and ``9``.
  53. Defaults to the tasks :attr:`~celery.task.base.Task.priority` attribute.
  54. :keyword serializer: A string identifying the default serialization
  55. method to use. Defaults to the ``CELERY_TASK_SERIALIZER`` setting.
  56. Can be ``pickle`` ``json``, ``yaml``, or any custom serialization
  57. methods that have been registered with
  58. :mod:`carrot.serialization.registry`. Defaults to the tasks
  59. :attr:`~celery.task.base.Task.serializer` attribute.
  60. **Note**: If the ``CELERY_ALWAYS_EAGER`` setting is set, it will be
  61. replaced by a local :func:`apply` call instead.
  62. """
  63. router = router or Router(conf.ROUTES, conf.get_queues(),
  64. conf.CREATE_MISSING_QUEUES)
  65. if conf.ALWAYS_EAGER:
  66. return apply(task, args, kwargs, task_id=task_id)
  67. task = tasks[task.name] # get instance from registry
  68. options = dict(extract_exec_options(task), **options)
  69. options = router.route(options, task.name, args, kwargs)
  70. exchange = options.get("exchange")
  71. exchange_type = options.get("exchange_type")
  72. publish = publisher or task.get_publisher(connection, exchange=exchange,
  73. exchange_type=exchange_type)
  74. try:
  75. task_id = publish.delay_task(task.name, args, kwargs, task_id=task_id,
  76. countdown=countdown, eta=eta, **options)
  77. finally:
  78. publisher or publish.close()
  79. return task.AsyncResult(task_id)
  80. @with_connection
  81. def send_task(name, args=None, kwargs=None, countdown=None, eta=None,
  82. task_id=None, publisher=None, connection=None, connect_timeout=None,
  83. result_cls=AsyncResult, **options):
  84. """Send task by name.
  85. Useful if you don't have access to the :class:`~celery.task.base.Task`
  86. class.
  87. :param name: Name of task to execute.
  88. Supports the same arguments as :func:`apply_async`.
  89. """
  90. exchange = options.get("exchange")
  91. exchange_type = options.get("exchange_type")
  92. publish = publisher or TaskPublisher(connection, exchange=exchange,
  93. exchange_type=exchange_type)
  94. try:
  95. task_id = publish.delay_task(name, args, kwargs, task_id=task_id,
  96. countdown=countdown, eta=eta, **options)
  97. finally:
  98. publisher or publish.close()
  99. return result_cls(task_id)
  100. def delay_task(task_name, *args, **kwargs):
  101. """Delay a task for execution by the ``celery`` daemon.
  102. :param task_name: the name of a task registered in the task registry.
  103. :param \*args: positional arguments to pass on to the task.
  104. :param \*\*kwargs: keyword arguments to pass on to the task.
  105. :raises celery.exceptions.NotRegistered: exception if no such task
  106. has been registered in the task registry.
  107. :returns :class:`celery.result.AsyncResult`:
  108. Example
  109. >>> r = delay_task("update_record", name="George Costanza", age=32)
  110. >>> r.ready()
  111. True
  112. >>> r.result
  113. "Record was updated"
  114. """
  115. return apply_async(tasks[task_name], args, kwargs)
  116. def apply(task, args, kwargs, **options):
  117. """Apply the task locally.
  118. :keyword throw: Re-raise task exceptions. Defaults to
  119. the ``CELERY_EAGER_PROPAGATES_EXCEPTIONS`` setting.
  120. This will block until the task completes, and returns a
  121. :class:`celery.result.EagerResult` instance.
  122. """
  123. args = args or []
  124. kwargs = kwargs or {}
  125. task_id = options.get("task_id", gen_unique_id())
  126. retries = options.get("retries", 0)
  127. throw = options.pop("throw", conf.EAGER_PROPAGATES_EXCEPTIONS)
  128. task = tasks[task.name] # Make sure we get the instance, not class.
  129. default_kwargs = {"task_name": task.name,
  130. "task_id": task_id,
  131. "task_retries": retries,
  132. "task_is_eager": True,
  133. "logfile": options.get("logfile"),
  134. "delivery_info": {"is_eager": True},
  135. "loglevel": options.get("loglevel", 0)}
  136. supported_keys = fun_takes_kwargs(task.run, default_kwargs)
  137. extend_with = dict((key, val) for key, val in default_kwargs.items()
  138. if key in supported_keys)
  139. kwargs.update(extend_with)
  140. trace = TaskTrace(task.name, task_id, args, kwargs, task=task)
  141. retval = trace.execute()
  142. if isinstance(retval, ExceptionInfo):
  143. if throw:
  144. raise retval.exception
  145. retval = retval.exception
  146. return EagerResult(task_id, retval, trace.status, traceback=trace.strtb)