1

I'm learning to use celery. I have a function (in a Flask application) in somewhat pseudocode from what I've learned so far:

def do_a_task_route():
    try:
        result = a_celery_task.apply_async(args=[request_data])
        returned = a_celery_task.AsyncResult(result.task_id).get(timeout = 2.0)
        return jsonify(response = returned['response'])
    except:
        return jsonify(response = "some big problem")

I'm not 100% sure this right and best, but works for me now. It seems that the result/returned lines could be one "returned = run_task" where run task does task and waits.

I was thinking on refactoring directions -- a) bundle those two lines (result/returned) in a function that runs a task and call the result or b) put the "AsyncResult" into the task itself and have that return.

What is the celery way from someone who has done this before? Or just some feedback from someone who has fine tuned celery before.

blueblank
  • 4,724
  • 9
  • 48
  • 73

1 Answers1

0

Refactoring this code only makes sense if you're going to reuse it elsewhere in your web application. There's no need to put these few lines in new functions if they're only going to be called from here. But if you intend to reuse the code then it's a good idea to have a function for starting that task and returning the response. I don't really think this is a question about Celery as these refactoring principles apply to any code.

Simeon Visser
  • 118,920
  • 18
  • 185
  • 180
  • Yes and no. I'm fishing for feedback from others who have written celery tasks as well as discussing how to refactor the pseudocode provided – blueblank Jun 08 '12 at 13:08