Development of an internal social media platform with personalised dashboards for students
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

task.py 35KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948
  1. # -*- coding: utf-8 -*-
  2. """
  3. celery.app.task
  4. ~~~~~~~~~~~~~~~
  5. Task Implementation: Task request context, and the base task class.
  6. """
  7. from __future__ import absolute_import
  8. import sys
  9. from billiard.einfo import ExceptionInfo
  10. from celery import current_app
  11. from celery import states
  12. from celery._state import _task_stack
  13. from celery.canvas import signature
  14. from celery.exceptions import MaxRetriesExceededError, Reject, Retry
  15. from celery.five import class_property, items, with_metaclass
  16. from celery.local import Proxy
  17. from celery.result import EagerResult
  18. from celery.utils import gen_task_name, fun_takes_kwargs, uuid, maybe_reraise
  19. from celery.utils.functional import mattrgetter, maybe_list
  20. from celery.utils.imports import instantiate
  21. from celery.utils.mail import ErrorMail
  22. from .annotations import resolve_all as resolve_all_annotations
  23. from .registry import _unpickle_task_v2
  24. from .utils import appstr
  25. __all__ = ['Context', 'Task']
  26. #: extracts attributes related to publishing a message from an object.
  27. extract_exec_options = mattrgetter(
  28. 'queue', 'routing_key', 'exchange', 'priority', 'expires',
  29. 'serializer', 'delivery_mode', 'compression', 'time_limit',
  30. 'soft_time_limit', 'immediate', 'mandatory', # imm+man is deprecated
  31. )
  32. # We take __repr__ very seriously around here ;)
  33. R_BOUND_TASK = '<class {0.__name__} of {app}{flags}>'
  34. R_UNBOUND_TASK = '<unbound {0.__name__}{flags}>'
  35. R_SELF_TASK = '<@task {0.name} bound to other {0.__self__}>'
  36. R_INSTANCE = '<@task: {0.name} of {app}{flags}>'
  37. class _CompatShared(object):
  38. def __init__(self, name, cons):
  39. self.name = name
  40. self.cons = cons
  41. def __hash__(self):
  42. return hash(self.name)
  43. def __repr__(self):
  44. return '<OldTask: %r>' % (self.name, )
  45. def __call__(self, app):
  46. return self.cons(app)
  47. def _strflags(flags, default=''):
  48. if flags:
  49. return ' ({0})'.format(', '.join(flags))
  50. return default
  51. def _reprtask(task, fmt=None, flags=None):
  52. flags = list(flags) if flags is not None else []
  53. flags.append('v2 compatible') if task.__v2_compat__ else None
  54. if not fmt:
  55. fmt = R_BOUND_TASK if task._app else R_UNBOUND_TASK
  56. return fmt.format(
  57. task, flags=_strflags(flags),
  58. app=appstr(task._app) if task._app else None,
  59. )
  60. class Context(object):
  61. # Default context
  62. logfile = None
  63. loglevel = None
  64. hostname = None
  65. id = None
  66. args = None
  67. kwargs = None
  68. retries = 0
  69. eta = None
  70. expires = None
  71. is_eager = False
  72. headers = None
  73. delivery_info = None
  74. reply_to = None
  75. correlation_id = None
  76. taskset = None # compat alias to group
  77. group = None
  78. chord = None
  79. utc = None
  80. called_directly = True
  81. callbacks = None
  82. errbacks = None
  83. timelimit = None
  84. _children = None # see property
  85. _protected = 0
  86. def __init__(self, *args, **kwargs):
  87. self.update(*args, **kwargs)
  88. def update(self, *args, **kwargs):
  89. return self.__dict__.update(*args, **kwargs)
  90. def clear(self):
  91. return self.__dict__.clear()
  92. def get(self, key, default=None):
  93. return getattr(self, key, default)
  94. def __repr__(self):
  95. return '<Context: {0!r}>'.format(vars(self))
  96. @property
  97. def children(self):
  98. # children must be an empy list for every thread
  99. if self._children is None:
  100. self._children = []
  101. return self._children
  102. class TaskType(type):
  103. """Meta class for tasks.
  104. Automatically registers the task in the task registry (except
  105. if the :attr:`Task.abstract`` attribute is set).
  106. If no :attr:`Task.name` attribute is provided, then the name is generated
  107. from the module and class name.
  108. """
  109. _creation_count = {} # used by old non-abstract task classes
  110. def __new__(cls, name, bases, attrs):
  111. new = super(TaskType, cls).__new__
  112. task_module = attrs.get('__module__') or '__main__'
  113. # - Abstract class: abstract attribute should not be inherited.
  114. abstract = attrs.pop('abstract', None)
  115. if abstract or not attrs.get('autoregister', True):
  116. return new(cls, name, bases, attrs)
  117. # The 'app' attribute is now a property, with the real app located
  118. # in the '_app' attribute. Previously this was a regular attribute,
  119. # so we should support classes defining it.
  120. app = attrs.pop('_app', None) or attrs.pop('app', None)
  121. # Attempt to inherit app from one the bases
  122. if not isinstance(app, Proxy) and app is None:
  123. for base in bases:
  124. if getattr(base, '_app', None):
  125. app = base._app
  126. break
  127. else:
  128. app = current_app._get_current_object()
  129. attrs['_app'] = app
  130. # - Automatically generate missing/empty name.
  131. task_name = attrs.get('name')
  132. if not task_name:
  133. attrs['name'] = task_name = gen_task_name(app, name, task_module)
  134. if not attrs.get('_decorated'):
  135. # non decorated tasks must also be shared in case
  136. # an app is created multiple times due to modules
  137. # imported under multiple names.
  138. # Hairy stuff, here to be compatible with 2.x.
  139. # People should not use non-abstract task classes anymore,
  140. # use the task decorator.
  141. from celery._state import connect_on_app_finalize
  142. unique_name = '.'.join([task_module, name])
  143. if unique_name not in cls._creation_count:
  144. # the creation count is used as a safety
  145. # so that the same task is not added recursively
  146. # to the set of constructors.
  147. cls._creation_count[unique_name] = 1
  148. connect_on_app_finalize(_CompatShared(
  149. unique_name,
  150. lambda app: TaskType.__new__(cls, name, bases,
  151. dict(attrs, _app=app)),
  152. ))
  153. # - Create and register class.
  154. # Because of the way import happens (recursively)
  155. # we may or may not be the first time the task tries to register
  156. # with the framework. There should only be one class for each task
  157. # name, so we always return the registered version.
  158. tasks = app._tasks
  159. if task_name not in tasks:
  160. tasks.register(new(cls, name, bases, attrs))
  161. instance = tasks[task_name]
  162. instance.bind(app)
  163. return instance.__class__
  164. def __repr__(cls):
  165. return _reprtask(cls)
  166. @with_metaclass(TaskType)
  167. class Task(object):
  168. """Task base class.
  169. When called tasks apply the :meth:`run` method. This method must
  170. be defined by all tasks (that is unless the :meth:`__call__` method
  171. is overridden).
  172. """
  173. __trace__ = None
  174. __v2_compat__ = False # set by old base in celery.task.base
  175. ErrorMail = ErrorMail
  176. MaxRetriesExceededError = MaxRetriesExceededError
  177. #: Execution strategy used, or the qualified name of one.
  178. Strategy = 'celery.worker.strategy:default'
  179. #: This is the instance bound to if the task is a method of a class.
  180. __self__ = None
  181. #: The application instance associated with this task class.
  182. _app = None
  183. #: Name of the task.
  184. name = None
  185. #: If :const:`True` the task is an abstract base class.
  186. abstract = True
  187. #: If disabled the worker will not forward magic keyword arguments.
  188. #: Deprecated and scheduled for removal in v4.0.
  189. accept_magic_kwargs = False
  190. #: Maximum number of retries before giving up. If set to :const:`None`,
  191. #: it will **never** stop retrying.
  192. max_retries = 3
  193. #: Default time in seconds before a retry of the task should be
  194. #: executed. 3 minutes by default.
  195. default_retry_delay = 3 * 60
  196. #: Rate limit for this task type. Examples: :const:`None` (no rate
  197. #: limit), `'100/s'` (hundred tasks a second), `'100/m'` (hundred tasks
  198. #: a minute),`'100/h'` (hundred tasks an hour)
  199. rate_limit = None
  200. #: If enabled the worker will not store task state and return values
  201. #: for this task. Defaults to the :setting:`CELERY_IGNORE_RESULT`
  202. #: setting.
  203. ignore_result = None
  204. #: If enabled the request will keep track of subtasks started by
  205. #: this task, and this information will be sent with the result
  206. #: (``result.children``).
  207. trail = True
  208. #: If enabled the worker will send monitoring events related to
  209. #: this task (but only if the worker is configured to send
  210. #: task related events).
  211. #: Note that this has no effect on the task-failure event case
  212. #: where a task is not registered (as it will have no task class
  213. #: to check this flag).
  214. send_events = True
  215. #: When enabled errors will be stored even if the task is otherwise
  216. #: configured to ignore results.
  217. store_errors_even_if_ignored = None
  218. #: If enabled an email will be sent to :setting:`ADMINS` whenever a task
  219. #: of this type fails.
  220. send_error_emails = None
  221. #: The name of a serializer that are registered with
  222. #: :mod:`kombu.serialization.registry`. Default is `'pickle'`.
  223. serializer = None
  224. #: Hard time limit.
  225. #: Defaults to the :setting:`CELERYD_TASK_TIME_LIMIT` setting.
  226. time_limit = None
  227. #: Soft time limit.
  228. #: Defaults to the :setting:`CELERYD_TASK_SOFT_TIME_LIMIT` setting.
  229. soft_time_limit = None
  230. #: The result store backend used for this task.
  231. backend = None
  232. #: If disabled this task won't be registered automatically.
  233. autoregister = True
  234. #: If enabled the task will report its status as 'started' when the task
  235. #: is executed by a worker. Disabled by default as the normal behaviour
  236. #: is to not report that level of granularity. Tasks are either pending,
  237. #: finished, or waiting to be retried.
  238. #:
  239. #: Having a 'started' status can be useful for when there are long
  240. #: running tasks and there is a need to report which task is currently
  241. #: running.
  242. #:
  243. #: The application default can be overridden using the
  244. #: :setting:`CELERY_TRACK_STARTED` setting.
  245. track_started = None
  246. #: When enabled messages for this task will be acknowledged **after**
  247. #: the task has been executed, and not *just before* which is the
  248. #: default behavior.
  249. #:
  250. #: Please note that this means the task may be executed twice if the
  251. #: worker crashes mid execution (which may be acceptable for some
  252. #: applications).
  253. #:
  254. #: The application default can be overridden with the
  255. #: :setting:`CELERY_ACKS_LATE` setting.
  256. acks_late = None
  257. #: Tuple of expected exceptions.
  258. #:
  259. #: These are errors that are expected in normal operation
  260. #: and that should not be regarded as a real error by the worker.
  261. #: Currently this means that the state will be updated to an error
  262. #: state, but the worker will not log the event as an error.
  263. throws = ()
  264. #: Default task expiry time.
  265. expires = None
  266. #: Some may expect a request to exist even if the task has not been
  267. #: called. This should probably be deprecated.
  268. _default_request = None
  269. _exec_options = None
  270. __bound__ = False
  271. from_config = (
  272. ('send_error_emails', 'CELERY_SEND_TASK_ERROR_EMAILS'),
  273. ('serializer', 'CELERY_TASK_SERIALIZER'),
  274. ('rate_limit', 'CELERY_DEFAULT_RATE_LIMIT'),
  275. ('track_started', 'CELERY_TRACK_STARTED'),
  276. ('acks_late', 'CELERY_ACKS_LATE'),
  277. ('ignore_result', 'CELERY_IGNORE_RESULT'),
  278. ('store_errors_even_if_ignored',
  279. 'CELERY_STORE_ERRORS_EVEN_IF_IGNORED'),
  280. )
  281. _backend = None # set by backend property.
  282. __bound__ = False
  283. # - Tasks are lazily bound, so that configuration is not set
  284. # - until the task is actually used
  285. @classmethod
  286. def bind(self, app):
  287. was_bound, self.__bound__ = self.__bound__, True
  288. self._app = app
  289. conf = app.conf
  290. self._exec_options = None # clear option cache
  291. for attr_name, config_name in self.from_config:
  292. if getattr(self, attr_name, None) is None:
  293. setattr(self, attr_name, conf[config_name])
  294. if self.accept_magic_kwargs is None:
  295. self.accept_magic_kwargs = app.accept_magic_kwargs
  296. # decorate with annotations from config.
  297. if not was_bound:
  298. self.annotate()
  299. from celery.utils.threads import LocalStack
  300. self.request_stack = LocalStack()
  301. # PeriodicTask uses this to add itself to the PeriodicTask schedule.
  302. self.on_bound(app)
  303. return app
  304. @classmethod
  305. def on_bound(self, app):
  306. """This method can be defined to do additional actions when the
  307. task class is bound to an app."""
  308. pass
  309. @classmethod
  310. def _get_app(self):
  311. if self._app is None:
  312. self._app = current_app
  313. if not self.__bound__:
  314. # The app property's __set__ method is not called
  315. # if Task.app is set (on the class), so must bind on use.
  316. self.bind(self._app)
  317. return self._app
  318. app = class_property(_get_app, bind)
  319. @classmethod
  320. def annotate(self):
  321. for d in resolve_all_annotations(self.app.annotations, self):
  322. for key, value in items(d):
  323. if key.startswith('@'):
  324. self.add_around(key[1:], value)
  325. else:
  326. setattr(self, key, value)
  327. @classmethod
  328. def add_around(self, attr, around):
  329. orig = getattr(self, attr)
  330. if getattr(orig, '__wrapped__', None):
  331. orig = orig.__wrapped__
  332. meth = around(orig)
  333. meth.__wrapped__ = orig
  334. setattr(self, attr, meth)
  335. def __call__(self, *args, **kwargs):
  336. _task_stack.push(self)
  337. self.push_request()
  338. try:
  339. # add self if this is a bound task
  340. if self.__self__ is not None:
  341. return self.run(self.__self__, *args, **kwargs)
  342. return self.run(*args, **kwargs)
  343. finally:
  344. self.pop_request()
  345. _task_stack.pop()
  346. def __reduce__(self):
  347. # - tasks are pickled into the name of the task only, and the reciever
  348. # - simply grabs it from the local registry.
  349. # - in later versions the module of the task is also included,
  350. # - and the receiving side tries to import that module so that
  351. # - it will work even if the task has not been registered.
  352. mod = type(self).__module__
  353. mod = mod if mod and mod in sys.modules else None
  354. return (_unpickle_task_v2, (self.name, mod), None)
  355. def run(self, *args, **kwargs):
  356. """The body of the task executed by workers."""
  357. raise NotImplementedError('Tasks must define the run method.')
  358. def start_strategy(self, app, consumer, **kwargs):
  359. return instantiate(self.Strategy, self, app, consumer, **kwargs)
  360. def delay(self, *args, **kwargs):
  361. """Star argument version of :meth:`apply_async`.
  362. Does not support the extra options enabled by :meth:`apply_async`.
  363. :param \*args: positional arguments passed on to the task.
  364. :param \*\*kwargs: keyword arguments passed on to the task.
  365. :returns :class:`celery.result.AsyncResult`:
  366. """
  367. return self.apply_async(args, kwargs)
  368. def apply_async(self, args=None, kwargs=None, task_id=None, producer=None,
  369. link=None, link_error=None, **options):
  370. """Apply tasks asynchronously by sending a message.
  371. :keyword args: The positional arguments to pass on to the
  372. task (a :class:`list` or :class:`tuple`).
  373. :keyword kwargs: The keyword arguments to pass on to the
  374. task (a :class:`dict`)
  375. :keyword countdown: Number of seconds into the future that the
  376. task should execute. Defaults to immediate
  377. execution.
  378. :keyword eta: A :class:`~datetime.datetime` object describing
  379. the absolute time and date of when the task should
  380. be executed. May not be specified if `countdown`
  381. is also supplied.
  382. :keyword expires: Either a :class:`int`, describing the number of
  383. seconds, or a :class:`~datetime.datetime` object
  384. that describes the absolute time and date of when
  385. the task should expire. The task will not be
  386. executed after the expiration time.
  387. :keyword connection: Re-use existing broker connection instead
  388. of establishing a new one.
  389. :keyword retry: If enabled sending of the task message will be retried
  390. in the event of connection loss or failure. Default
  391. is taken from the :setting:`CELERY_TASK_PUBLISH_RETRY`
  392. setting. Note that you need to handle the
  393. producer/connection manually for this to work.
  394. :keyword retry_policy: Override the retry policy used. See the
  395. :setting:`CELERY_TASK_PUBLISH_RETRY_POLICY`
  396. setting.
  397. :keyword routing_key: Custom routing key used to route the task to a
  398. worker server. If in combination with a
  399. ``queue`` argument only used to specify custom
  400. routing keys to topic exchanges.
  401. :keyword queue: The queue to route the task to. This must be a key
  402. present in :setting:`CELERY_QUEUES`, or
  403. :setting:`CELERY_CREATE_MISSING_QUEUES` must be
  404. enabled. See :ref:`guide-routing` for more
  405. information.
  406. :keyword exchange: Named custom exchange to send the task to.
  407. Usually not used in combination with the ``queue``
  408. argument.
  409. :keyword priority: The task priority, a number between 0 and 9.
  410. Defaults to the :attr:`priority` attribute.
  411. :keyword serializer: A string identifying the default
  412. serialization method to use. Can be `pickle`,
  413. `json`, `yaml`, `msgpack` or any custom
  414. serialization method that has been registered
  415. with :mod:`kombu.serialization.registry`.
  416. Defaults to the :attr:`serializer` attribute.
  417. :keyword compression: A string identifying the compression method
  418. to use. Can be one of ``zlib``, ``bzip2``,
  419. or any custom compression methods registered with
  420. :func:`kombu.compression.register`. Defaults to
  421. the :setting:`CELERY_MESSAGE_COMPRESSION`
  422. setting.
  423. :keyword link: A single, or a list of tasks to apply if the
  424. task exits successfully.
  425. :keyword link_error: A single, or a list of tasks to apply
  426. if an error occurs while executing the task.
  427. :keyword producer: :class:~@amqp.TaskProducer` instance to use.
  428. :keyword add_to_parent: If set to True (default) and the task
  429. is applied while executing another task, then the result
  430. will be appended to the parent tasks ``request.children``
  431. attribute. Trailing can also be disabled by default using the
  432. :attr:`trail` attribute
  433. :keyword publisher: Deprecated alias to ``producer``.
  434. :keyword headers: Message headers to be sent in the
  435. task (a :class:`dict`)
  436. :rtype :class:`celery.result.AsyncResult`: if
  437. :setting:`CELERY_ALWAYS_EAGER` is not set, otherwise
  438. :class:`celery.result.EagerResult`.
  439. Also supports all keyword arguments supported by
  440. :meth:`kombu.Producer.publish`.
  441. .. note::
  442. If the :setting:`CELERY_ALWAYS_EAGER` setting is set, it will
  443. be replaced by a local :func:`apply` call instead.
  444. """
  445. app = self._get_app()
  446. if app.conf.CELERY_ALWAYS_EAGER:
  447. return self.apply(args, kwargs, task_id=task_id or uuid(),
  448. link=link, link_error=link_error, **options)
  449. # add 'self' if this is a "task_method".
  450. if self.__self__ is not None:
  451. args = args if isinstance(args, tuple) else tuple(args or ())
  452. args = (self.__self__, ) + args
  453. return app.send_task(
  454. self.name, args, kwargs, task_id=task_id, producer=producer,
  455. link=link, link_error=link_error, result_cls=self.AsyncResult,
  456. **dict(self._get_exec_options(), **options)
  457. )
  458. def subtask_from_request(self, request=None, args=None, kwargs=None,
  459. queue=None, **extra_options):
  460. request = self.request if request is None else request
  461. args = request.args if args is None else args
  462. kwargs = request.kwargs if kwargs is None else kwargs
  463. limit_hard, limit_soft = request.timelimit or (None, None)
  464. options = {
  465. 'task_id': request.id,
  466. 'link': request.callbacks,
  467. 'link_error': request.errbacks,
  468. 'group_id': request.group,
  469. 'chord': request.chord,
  470. 'soft_time_limit': limit_soft,
  471. 'time_limit': limit_hard,
  472. 'reply_to': request.reply_to,
  473. 'headers': request.headers,
  474. }
  475. options.update(
  476. {'queue': queue} if queue else (request.delivery_info or {})
  477. )
  478. return self.subtask(args, kwargs, options, type=self, **extra_options)
  479. def retry(self, args=None, kwargs=None, exc=None, throw=True,
  480. eta=None, countdown=None, max_retries=None, **options):
  481. """Retry the task.
  482. :param args: Positional arguments to retry with.
  483. :param kwargs: Keyword arguments to retry with.
  484. :keyword exc: Custom exception to report when the max restart
  485. limit has been exceeded (default:
  486. :exc:`~@MaxRetriesExceededError`).
  487. If this argument is set and retry is called while
  488. an exception was raised (``sys.exc_info()`` is set)
  489. it will attempt to reraise the current exception.
  490. If no exception was raised it will raise the ``exc``
  491. argument provided.
  492. :keyword countdown: Time in seconds to delay the retry for.
  493. :keyword eta: Explicit time and date to run the retry at
  494. (must be a :class:`~datetime.datetime` instance).
  495. :keyword max_retries: If set, overrides the default retry limit for
  496. this execution. Changes to this parameter do not propagate to
  497. subsequent task retry attempts. A value of :const:`None`, means
  498. "use the default", so if you want infinite retries you would
  499. have to set the :attr:`max_retries` attribute of the task to
  500. :const:`None` first.
  501. :keyword time_limit: If set, overrides the default time limit.
  502. :keyword soft_time_limit: If set, overrides the default soft
  503. time limit.
  504. :keyword \*\*options: Any extra options to pass on to
  505. meth:`apply_async`.
  506. :keyword throw: If this is :const:`False`, do not raise the
  507. :exc:`~@Retry` exception,
  508. that tells the worker to mark the task as being
  509. retried. Note that this means the task will be
  510. marked as failed if the task raises an exception,
  511. or successful if it returns.
  512. :raises celery.exceptions.Retry: To tell the worker that
  513. the task has been re-sent for retry. This always happens,
  514. unless the `throw` keyword argument has been explicitly set
  515. to :const:`False`, and is considered normal operation.
  516. **Example**
  517. .. code-block:: python
  518. >>> from imaginary_twitter_lib import Twitter
  519. >>> from proj.celery import app
  520. >>> @app.task(bind=True)
  521. ... def tweet(self, auth, message):
  522. ... twitter = Twitter(oauth=auth)
  523. ... try:
  524. ... twitter.post_status_update(message)
  525. ... except twitter.FailWhale as exc:
  526. ... # Retry in 5 minutes.
  527. ... raise self.retry(countdown=60 * 5, exc=exc)
  528. Although the task will never return above as `retry` raises an
  529. exception to notify the worker, we use `raise` in front of the retry
  530. to convey that the rest of the block will not be executed.
  531. """
  532. request = self.request
  533. retries = request.retries + 1
  534. max_retries = self.max_retries if max_retries is None else max_retries
  535. # Not in worker or emulated by (apply/always_eager),
  536. # so just raise the original exception.
  537. if request.called_directly:
  538. maybe_reraise() # raise orig stack if PyErr_Occurred
  539. raise exc or Retry('Task can be retried', None)
  540. if not eta and countdown is None:
  541. countdown = self.default_retry_delay
  542. is_eager = request.is_eager
  543. S = self.subtask_from_request(
  544. request, args, kwargs,
  545. countdown=countdown, eta=eta, retries=retries,
  546. **options
  547. )
  548. if max_retries is not None and retries > max_retries:
  549. if exc:
  550. # first try to reraise the original exception
  551. maybe_reraise()
  552. # or if not in an except block then raise the custom exc.
  553. raise exc
  554. raise self.MaxRetriesExceededError(
  555. "Can't retry {0}[{1}] args:{2} kwargs:{3}".format(
  556. self.name, request.id, S.args, S.kwargs))
  557. ret = Retry(exc=exc, when=eta or countdown)
  558. if is_eager:
  559. # if task was executed eagerly using apply(),
  560. # then the retry must also be executed eagerly.
  561. S.apply().get()
  562. return ret
  563. try:
  564. S.apply_async()
  565. except Exception as exc:
  566. raise Reject(exc, requeue=False)
  567. if throw:
  568. raise ret
  569. return ret
  570. def apply(self, args=None, kwargs=None,
  571. link=None, link_error=None, **options):
  572. """Execute this task locally, by blocking until the task returns.
  573. :param args: positional arguments passed on to the task.
  574. :param kwargs: keyword arguments passed on to the task.
  575. :keyword throw: Re-raise task exceptions. Defaults to
  576. the :setting:`CELERY_EAGER_PROPAGATES_EXCEPTIONS`
  577. setting.
  578. :rtype :class:`celery.result.EagerResult`:
  579. """
  580. # trace imports Task, so need to import inline.
  581. from celery.app.trace import eager_trace_task
  582. app = self._get_app()
  583. args = args or ()
  584. # add 'self' if this is a bound method.
  585. if self.__self__ is not None:
  586. args = (self.__self__, ) + tuple(args)
  587. kwargs = kwargs or {}
  588. task_id = options.get('task_id') or uuid()
  589. retries = options.get('retries', 0)
  590. throw = app.either('CELERY_EAGER_PROPAGATES_EXCEPTIONS',
  591. options.pop('throw', None))
  592. # Make sure we get the task instance, not class.
  593. task = app._tasks[self.name]
  594. request = {'id': task_id,
  595. 'retries': retries,
  596. 'is_eager': True,
  597. 'logfile': options.get('logfile'),
  598. 'loglevel': options.get('loglevel', 0),
  599. 'callbacks': maybe_list(link),
  600. 'errbacks': maybe_list(link_error),
  601. 'headers': options.get('headers'),
  602. 'delivery_info': {'is_eager': True}}
  603. if self.accept_magic_kwargs:
  604. default_kwargs = {'task_name': task.name,
  605. 'task_id': task_id,
  606. 'task_retries': retries,
  607. 'task_is_eager': True,
  608. 'logfile': options.get('logfile'),
  609. 'loglevel': options.get('loglevel', 0),
  610. 'delivery_info': {'is_eager': True}}
  611. supported_keys = fun_takes_kwargs(task.run, default_kwargs)
  612. extend_with = dict((key, val)
  613. for key, val in items(default_kwargs)
  614. if key in supported_keys)
  615. kwargs.update(extend_with)
  616. tb = None
  617. retval, info = eager_trace_task(task, task_id, args, kwargs,
  618. app=self._get_app(),
  619. request=request, propagate=throw)
  620. if isinstance(retval, ExceptionInfo):
  621. retval, tb = retval.exception, retval.traceback
  622. state = states.SUCCESS if info is None else info.state
  623. return EagerResult(task_id, retval, state, traceback=tb)
  624. def AsyncResult(self, task_id, **kwargs):
  625. """Get AsyncResult instance for this kind of task.
  626. :param task_id: Task id to get result for.
  627. """
  628. return self._get_app().AsyncResult(task_id, backend=self.backend,
  629. task_name=self.name, **kwargs)
  630. def subtask(self, args=None, *starargs, **starkwargs):
  631. """Return :class:`~celery.signature` object for
  632. this task, wrapping arguments and execution options
  633. for a single task invocation."""
  634. starkwargs.setdefault('app', self.app)
  635. return signature(self, args, *starargs, **starkwargs)
  636. def s(self, *args, **kwargs):
  637. """``.s(*a, **k) -> .subtask(a, k)``"""
  638. return self.subtask(args, kwargs)
  639. def si(self, *args, **kwargs):
  640. """``.si(*a, **k) -> .subtask(a, k, immutable=True)``"""
  641. return self.subtask(args, kwargs, immutable=True)
  642. def chunks(self, it, n):
  643. """Creates a :class:`~celery.canvas.chunks` task for this task."""
  644. from celery import chunks
  645. return chunks(self.s(), it, n, app=self.app)
  646. def map(self, it):
  647. """Creates a :class:`~celery.canvas.xmap` task from ``it``."""
  648. from celery import xmap
  649. return xmap(self.s(), it, app=self.app)
  650. def starmap(self, it):
  651. """Creates a :class:`~celery.canvas.xstarmap` task from ``it``."""
  652. from celery import xstarmap
  653. return xstarmap(self.s(), it, app=self.app)
  654. def send_event(self, type_, **fields):
  655. req = self.request
  656. with self.app.events.default_dispatcher(hostname=req.hostname) as d:
  657. return d.send(type_, uuid=req.id, **fields)
  658. def update_state(self, task_id=None, state=None, meta=None):
  659. """Update task state.
  660. :keyword task_id: Id of the task to update, defaults to the
  661. id of the current task
  662. :keyword state: New state (:class:`str`).
  663. :keyword meta: State metadata (:class:`dict`).
  664. """
  665. if task_id is None:
  666. task_id = self.request.id
  667. self.backend.store_result(task_id, meta, state)
  668. def on_success(self, retval, task_id, args, kwargs):
  669. """Success handler.
  670. Run by the worker if the task executes successfully.
  671. :param retval: The return value of the task.
  672. :param task_id: Unique id of the executed task.
  673. :param args: Original arguments for the executed task.
  674. :param kwargs: Original keyword arguments for the executed task.
  675. The return value of this handler is ignored.
  676. """
  677. pass
  678. def on_retry(self, exc, task_id, args, kwargs, einfo):
  679. """Retry handler.
  680. This is run by the worker when the task is to be retried.
  681. :param exc: The exception sent to :meth:`retry`.
  682. :param task_id: Unique id of the retried task.
  683. :param args: Original arguments for the retried task.
  684. :param kwargs: Original keyword arguments for the retried task.
  685. :keyword einfo: :class:`~billiard.einfo.ExceptionInfo`
  686. instance, containing the traceback.
  687. The return value of this handler is ignored.
  688. """
  689. pass
  690. def on_failure(self, exc, task_id, args, kwargs, einfo):
  691. """Error handler.
  692. This is run by the worker when the task fails.
  693. :param exc: The exception raised by the task.
  694. :param task_id: Unique id of the failed task.
  695. :param args: Original arguments for the task that failed.
  696. :param kwargs: Original keyword arguments for the task
  697. that failed.
  698. :keyword einfo: :class:`~billiard.einfo.ExceptionInfo`
  699. instance, containing the traceback.
  700. The return value of this handler is ignored.
  701. """
  702. pass
  703. def after_return(self, status, retval, task_id, args, kwargs, einfo):
  704. """Handler called after the task returns.
  705. :param status: Current task state.
  706. :param retval: Task return value/exception.
  707. :param task_id: Unique id of the task.
  708. :param args: Original arguments for the task.
  709. :param kwargs: Original keyword arguments for the task.
  710. :keyword einfo: :class:`~billiard.einfo.ExceptionInfo`
  711. instance, containing the traceback (if any).
  712. The return value of this handler is ignored.
  713. """
  714. pass
  715. def send_error_email(self, context, exc, **kwargs):
  716. if self.send_error_emails and \
  717. not getattr(self, 'disable_error_emails', None):
  718. self.ErrorMail(self, **kwargs).send(context, exc)
  719. def add_trail(self, result):
  720. if self.trail:
  721. self.request.children.append(result)
  722. return result
  723. def push_request(self, *args, **kwargs):
  724. self.request_stack.push(Context(*args, **kwargs))
  725. def pop_request(self):
  726. self.request_stack.pop()
  727. def __repr__(self):
  728. """`repr(task)`"""
  729. return _reprtask(self, R_SELF_TASK if self.__self__ else R_INSTANCE)
  730. def _get_request(self):
  731. """Get current request object."""
  732. req = self.request_stack.top
  733. if req is None:
  734. # task was not called, but some may still expect a request
  735. # to be there, perhaps that should be deprecated.
  736. if self._default_request is None:
  737. self._default_request = Context()
  738. return self._default_request
  739. return req
  740. request = property(_get_request)
  741. def _get_exec_options(self):
  742. if self._exec_options is None:
  743. self._exec_options = extract_exec_options(self)
  744. return self._exec_options
  745. @property
  746. def backend(self):
  747. backend = self._backend
  748. if backend is None:
  749. return self.app.backend
  750. return backend
  751. @backend.setter
  752. def backend(self, value): # noqa
  753. self._backend = value
  754. @property
  755. def __name__(self):
  756. return self.__class__.__name__
  757. BaseTask = Task # compat alias