remote-tasks.rst 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  1. ==============
  2. Remote Tasks
  3. ==============
  4. .. module:: celery.task.http
  5. Executing tasks on a remote web server
  6. --------------------------------------
  7. If you need to call into another language, framework or similar, you can
  8. do so by using HTTP callback tasks.
  9. The HTTP callback tasks uses GET/POST arguments and uses a simple JSON response
  10. to return results. The scheme to call a task is::
  11. GET http://example.com/mytask/?arg1=a,arg2=b,arg3=c
  12. or using POST::
  13. POST http://example.com/mytask
  14. Whether to use GET or POST is up to you and your requirements.
  15. The web page should then return a response in the following format
  16. if the execution was successful::
  17. {"status": "success", "retval": ....}
  18. or if there was an error::
  19. {"status": "failure": "reason": "Invalid moon alignment."}
  20. With this information you could define a simple task in Django:
  21. .. code-block:: python
  22. from django.http import HttpResponse
  23. from anyjson import serialize
  24. def multiply(request):
  25. x = int(request.GET["x"])
  26. y = int(request.GET["y"])
  27. result = x * y
  28. response = {"status": "success", "retval": result}
  29. return HttpResponse(serialize(response), mimetype="application/json")
  30. or in Ruby on Rails:
  31. .. code-block:: ruby
  32. def multiply
  33. @x = params[:x].to_i
  34. @y = params[:y].to_i
  35. @status = {:status => "success", :retval => @x * @y}
  36. render :json => @status
  37. end
  38. You can easily port this scheme to any language/framework;
  39. New examples and libraries are very welcome.
  40. To execute the task you use the :class:`URL` class:
  41. >>> from celery.task.http import URL
  42. >>> res = URL("http://example.com/multiply").get_async(x=10, y=10)
  43. :class:`URL` is a shortcut to the :class:`HttpDispatchTask`. You can subclass this to extend the
  44. functionality.
  45. >>> from celery.task.http import HttpDispatchTask
  46. >>> res = HttpDispatchTask.delay(url="http://example.com/multiply", method="GET", x=10, y=10)
  47. >>> res.get()
  48. 100
  49. The output of celeryd (or the logfile if you've enabled it) should show the task being processed::
  50. [INFO/MainProcess] Task celery.task.http.HttpDispatchTask
  51. [f2cc8efc-2a14-40cd-85ad-f1c77c94beeb] processed: 100
  52. Since applying tasks can be done via HTTP using the
  53. ``celery.views.apply`` view, executing tasks from other languages is easy.
  54. For an example service exposing tasks via HTTP you should have a look at
  55. ``examples/celery_http_gateway``.