将 POST 请求从 Flask 传递到 Celery 任务

发布于 2025-01-16 19:36:43 字数 867 浏览 1 评论 0原文

我在 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

烈酒灼喉 2025-01-23 19:36:43

您的代码通常看起来是正确的。也就是说,确保 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 of delay since that gives you some finer grained control over the queue and countdown parameters.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文