'Pass a POST request from Flask to a Celery task
I have a long csv file upload task in Flask, and since it's long, I'd like to let Celery process it in the background, but how do I pass this request from the Flask route to a Celery task?
To build the route I followed the Flask documentation: https://flask.palletsprojects.com/en/2.0.x/patterns/fileuploads/
To configure Celery with Flask, I followed this tutorial by Miguel: https://blog.miguelgrinberg.com/post/celery-and-the-flask-application-factory-pattern
Based on the upload_file() route from the documentation, it would only have one task call to a Celery task:
@app.route('/', methods=['GET', 'POST'])
def upload_file():
task = upload_file_task.delay(...)
return jsonify({'task_id': task.id}), 202
And now the upload_file_task() function does everything the upload_file() route would do
Solution 1:[1]
Your code generally looks correct. That said, making sure celery runs correctly in production may be additional steps. You may also want to consider using the apply_async function instead of delay since that gives you some finer grained control over the queue and countdown parameters.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | 2ps |
