Преглед изворни кода

celery.views: Added decorator task_view that given a task, returns a view
applying the task and returns a JSON structure containing the keys "ok", and
"task_id".

Ask Solem пре 15 година
родитељ
комит
e7e007a4f5
1 измењених фајлова са 27 додато и 11 уклоњено
  1. 27 11
      celery/views.py

+ 27 - 11
celery/views.py

@@ -2,6 +2,7 @@
 from django.http import HttpResponse, Http404
 
 from anyjson import serialize as JSON_dump
+from billiard.utils.functional import wraps
 
 from celery.utils import get_full_cls_name
 from celery.result import AsyncResult
@@ -9,7 +10,30 @@ from celery.registry import tasks
 from celery.backends import default_backend
 
 
-def apply(request, task_name, args):
+def task_view(task):
+    """Decorator turning a task into a view that applies the task
+    asynchronusly.
+
+    :returns: a JSON dictionary containing the keys ``ok``, and
+        ``task_id``.
+
+    """
+
+    def _applier(request, **options):
+        kwargs = request.method == "POST" and \
+            request.POST.copy() or request.GET.copy()
+        kwargs = dict((key.encode("utf-8"), value)
+                    for key, value in kwargs.items())
+
+        result = task.apply_async(kwargs=kwargs)
+        response_data = {"ok": "true", "task_id": result.task_id}
+        return HttpResponse(JSON_dump(response_data), mimetype="application/json")
+
+    return _applier
+
+
+
+def apply(request, task_name):
     """View applying a task.
 
     Example:
@@ -19,18 +43,10 @@ def apply(request, task_name, args):
     without ensuring your code is safe!
 
     """
-    args = args.split("/")
-    kwargs = request.method == "POST" and \
-            request.POST.copy() or request.GET.copy()
-    kwargs = dict((key.encode("utf-8"), value)
-                    for key, value in kwargs.items())
+    task = tasks[task_name]
     if task_name not in tasks:
         raise Http404("apply: no such task")
-
-    task = tasks[task_name]
-    result = task.apply_async(args=args, kwargs=kwargs)
-    response_data = {"ok": "true", "task_id": result.task_id}
-    return HttpResponse(JSON_dump(response_data), mimetype="application/json")
+    return task_view(task)(request)
 
 
 def is_task_successful(request, task_id):