remote-tasks.rst 2.5 KB

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