فهرست منبع

@tasks(bind=True) now binds the task to "self" (the task type instance)

Ask Solem 12 سال پیش
والد
کامیت
fe40ec4d85
6فایلهای تغییر یافته به همراه29 افزوده شده و 34 حذف شده
  1. 2 1
      celery/app/base.py
  2. 3 3
      docs/faq.rst
  3. 3 3
      docs/internals/deprecation.rst
  4. 1 1
      docs/userguide/application.rst
  5. 3 2
      docs/userguide/canvas.rst
  6. 17 24
      docs/userguide/tasks.rst

+ 2 - 1
celery/app/base.py

@@ -213,11 +213,12 @@ class Celery(object):
 
     def _task_from_fun(self, fun, **options):
         base = options.pop('base', None) or self.Task
+        bind = options.pop('bind', False)
 
         T = type(fun.__name__, (base, ), dict({
             'app': self,
             'accept_magic_kwargs': False,
-            'run': staticmethod(fun),
+            'run': fun if bind else staticmethod(fun),
             '__doc__': fun.__doc__,
             '__module__': fun.__module__}, **options))()
         task = self._tasks[T.name]  # return global instance.

+ 3 - 3
docs/faq.rst

@@ -623,9 +623,9 @@ How can I get the task id of the current task?
 
 **Answer**: The current id and more is available in the task request::
 
-    @celery.task
-    def mytask():
-        cache.set(mytask.request.id, "Running")
+    @celery.task(bind=True)
+    def mytask(self):
+        cache.set(self.request.id, "Running")
 
 For more information see :ref:`task-request-info`.
 

+ 3 - 3
docs/internals/deprecation.rst

@@ -104,9 +104,9 @@ should be rewritten into::
 
     from celery import task
 
-    @task()
-    def add(x, y):
-        print("My task id is {0.request.id}".format(add))
+    @task(bind=True)
+    def add(self, x, y):
+        print("My task id is {0.request.id}".format(self))
 
 
 Task attributes

+ 1 - 1
docs/userguide/application.rst

@@ -437,7 +437,7 @@ class: :class:`celery.Task`.
         abstract = True
 
         def __call__(self, *args, **kwargs):
-            print('TASK STARTING: {0.name}[{0.request.id}].format(self))
+            print('TASK STARTING: {0.name}[{0.request.id}]'.format(self))
             return self.run(*args, **kwargs)
 
 

+ 3 - 2
docs/userguide/canvas.rst

@@ -807,10 +807,11 @@ Example implementation:
 
 .. code-block:: python
 
-    def unlock_chord(taskset, callback, interval=1, max_retries=None):
+    @app.task(bind=True)
+    def unlock_chord(self, taskset, callback, interval=1, max_retries=None):
         if taskset.ready():
             return subtask(callback).delay(taskset.join())
-        raise unlock_chord.retry(countdown=interval, max_retries=max_retries)
+        raise self.retry(countdown=interval, max_retries=max_retries)
 
 
 This is used by all result backends except Redis and Memcached, which

+ 17 - 24
docs/userguide/tasks.rst

@@ -245,22 +245,14 @@ An example task accessing information in the context is:
 
 .. code-block:: python
 
-    @app.task
-    def dump_context(x, y):
+    @app.task(bind=True)
+    def dump_context(self, x, y):
         print('Executing task id {0.id}, args: {0.args!r} kwargs: {0.kwargs!r}'.format(
-                dump_context.request))
-
-
-:data:`~celery.current_task` can also be used:
+                self.request))
 
-.. code-block:: python
 
-    from celery import current_task
-
-    @app.task
-    def dump_context(x, y):
-        print('Executing task id {0.id}, args: {0.args!r} kwargs: {0.kwargs!r}'.format(
-                current_task.request))
+The ``bind`` argument means that the function will be a "bound method" so
+that you can access attributes and methods on the task type instance.
 
 .. _task-logging:
 
@@ -316,13 +308,13 @@ Here's an example using ``retry``:
 
 .. code-block:: python
 
-    @app.task
-    def send_twitter_status(oauth, tweet):
+    @app.task(bind=True)
+    def send_twitter_status(self, oauth, tweet):
         try:
             twitter = Twitter(oauth)
             twitter.update_status(tweet)
         except (Twitter.FailWhaleError, Twitter.LoginError) as exc:
-            raise send_twitter_status.retry(exc=exc)
+            raise self.retry(exc=exc)
 
 .. note::
 
@@ -335,6 +327,9 @@ Here's an example using ``retry``:
     This is normal operation and always happens unless the
     ``throw`` argument to retry is set to :const:`False`.
 
+The bind argument to the task decorator will give access to ``self`` (the
+task type instance).
+
 The ``exc`` method is used to pass exception information that is
 used in logs, and when storing task results.
 Both the exception and the traceback will
@@ -356,7 +351,7 @@ but this will not happen if:
 
     .. code-block:: python
 
-        send_twitter_status.retry(exc=Twitter.LoginError())
+        self.retry(exc=Twitter.LoginError())
 
     will raise the ``exc`` argument given.
 
@@ -376,13 +371,13 @@ override this default.
 
 .. code-block:: python
 
-    @app.task(default_retry_delay=30 * 60)  # retry in 30 minutes.
+    @app.task(bind=True, default_retry_delay=30 * 60)  # retry in 30 minutes.
     def add(x, y):
         try:
             ...
         except Exception as exc:
-            raise add.retry(exc=exc, countdown=60)  # override the default and
-                                                    # retry in 1 minute
+            raise self.retry(exc=exc, countdown=60)  # override the default and
+                                                     # retry in 1 minute
 
 .. _task-options:
 
@@ -725,12 +720,10 @@ which defines its own custom :state:`ABORTED` state.
 
 Use :meth:`~@Task.update_state` to update a task's state::
 
-    from celery import current_task
-
-    @app.task
+    @app.task(bind=True)
     def upload_files(filenames):
         for i, file in enumerate(filenames):
-            current_task.update_state(state='PROGRESS',
+            self.update_state(state='PROGRESS',
                 meta={'current': i, 'total': len(filenames)})