methods.py 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192
  1. # -*- coding: utf-8 -*-
  2. """
  3. celery.contrib.methods
  4. ======================
  5. Task decorator that supports creating tasks out of methods.
  6. Examples
  7. --------
  8. .. code-block:: python
  9. from celery.contrib.methods import task
  10. class X(object):
  11. @task()
  12. def add(self, x, y):
  13. return x + y
  14. or with any task decorator:
  15. .. code-block:: python
  16. from celery.contrib.methods import task_method
  17. class X(object):
  18. @celery.task(filter=task_method)
  19. def add(self, x, y):
  20. return x + y
  21. Caveats
  22. -------
  23. - Automatic naming won't be able to know what the class name is.
  24. The name will still be module_name + task_name,
  25. so two methods with the same name in the same module will collide
  26. so that only one task can run:
  27. .. code-block:: python
  28. class A(object):
  29. @task()
  30. def add(self, x, y):
  31. return x + y
  32. class B(object):
  33. @task()
  34. def add(self, x, y):
  35. return x + y
  36. would have to be written as:
  37. .. code-block:: python
  38. class A(object):
  39. @task(name='A.add')
  40. def add(self, x, y):
  41. return x + y
  42. class B(object):
  43. @task(name='B.add')
  44. def add(self, x, y):
  45. return x + y
  46. """
  47. from __future__ import absolute_import
  48. from functools import partial
  49. from celery import task as _task
  50. class task_method(object):
  51. def __init__(self, task, *args, **kwargs):
  52. self.task = task
  53. def __get__(self, obj, type=None):
  54. if obj is None:
  55. return self.task
  56. task = self.task.__class__()
  57. task.__self__ = obj
  58. return task
  59. task = partial(_task, filter=task_method)