0

I have an API route that calls a function (ie: doSomethingForALongTime) that takes some time to finish. If we assume that the function doesn't return anything to the client, is there a work around to just call the function and send the status code 200 while the function is doing it's job?

@application.route('/api', methods=['GET'])
def api_route():
    doSomethingForALongTime() 
    return 200

1 Answers1

1

Yes, with some caveats. The usual way to handle this is to use a 'task queue', such as celery or rq (there's a walk-through of how to use rq in chapter 22 of the flask mega tutorial). The approaches require that, at least, you have redis running, and are running separate worker processes.

The idea is hand a task off to the task queue in your handler (route), then return a response to the browser while a worker in a separate process picks the task up from the queue and runs it.

It's also possible to run a 'worker thread' in your app, and have the handler queue up work for it. I have a proof-of-concept for that here, with the caveat that I've only used it for personal apps. The caveat is that this is only really suitable for a personal webapp.

Dave W. Smith
  • 24,318
  • 4
  • 40
  • 46