将 POST 请求从 Flask 传递到 Celery 任务
我在 Flask 中有一个很长的 csv 文件上传任务,由于它很长,我想让 Celery 在后台处理它,但是如何将此请求从 Flask 路由传递到 Celery 任务?
为了构建路线,我遵循了 Flask 文档: https://flask.palletsprojects .com/en/2.0.x/patterns/fileuploads/
要使用 Flask 配置 Celery,我遵循了 Miguel 的教程:https://blog.miguelgrinberg.com/post/celery- and-the-flask-application-factory-pattern
基于文档中的 upload_file()
路由,它只会有一个对 Celery 任务的任务调用
@app.route('/', methods=['GET', 'POST'])
def upload_file():
task = upload_file_task.delay(...)
return jsonify({'task_id': task.id}), 202
: upload_file_task()
函数执行 upload_file()
路由执行的所有操作
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
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您的代码通常看起来是正确的。也就是说,确保 celery 在生产中正确运行可能是额外的步骤。您可能还需要考虑使用
apply_async
函数而不是delay
,因为这可以让您对队列和倒计时参数进行更细粒度的控制。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 ofdelay
since that gives you some finer grained control over the queue and countdown parameters.