remote-tasks.rst 2.5 KB

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