【问题标题】:Store result to database from celery worker vs return result将结果从 celery worker 存储到数据库与返回结果
【发布时间】:2017-09-08 22:32:00
【问题描述】:

我正在使用带有 Django 的 Celery 来处理某个任务,该任务返回一个 JSON 值,该值需要放入模型记录中。现在我看到 2 个选项可以将其持久保存在 Django 数据库中:

  1. 将记录的 ID 作为任务签名的一部分传递。然后 Celery 可以使用它来update 记录。
  2. 或者,我可以从任务返回结果并为 Celery 启用 django-db 结果后端,它将位于 Celery 自己的 task_result 表中。这意味着我必须将 AsyncResult Id 保留在记录中,每当客户端请求记录时,我都会查找该过程是否已完成。

对我来说,选项 1 似乎更好,但由于我近年来没有使用 Celery,我想知道它是否有缺点,和/或选项 2 更适合哪种情况。

谢谢!

【问题讨论】:

    标签: python django celery


    【解决方案1】:

    不,第一种方法没有任何问题。

    tasks.py 从 app.models 导入 your_model 从芹菜进口任务

    @task
    def update_model(id):
        model_obj = your_model.objects.get(id=id)
        #do your stuffs here...
    

    views.py

    from app.tasks import update_model
    
    def your_view(request):
        #your code
        update_model.delay(id_of_the_instance_you_want_to_update)
    

    您可以将此示例代码用于数据库中的原子提交。如果你担心的话。(取自芹菜docs

    from functools import partial
    from django.db import transaction
    
    from .models import Article, Log
    from .tasks import send_article_created_notification
    
    def create_article(request):
        with transaction.atomic():
            article = Article.objects.create(**request.POST)
            # send this task only if the rest of the transaction succeeds.
            transaction.on_commit(partial(
                send_article_created_notification.delay, article_id=article.pk))
            Log.objects.create(type=Log.ARTICLE_CREATED, object_pk=article.pk)
    

    【讨论】:

    • celery 文档链接已失效
    猜你喜欢
    • 2022-11-25
    • 1970-01-01
    • 1970-01-01
    • 2013-06-21
    • 1970-01-01
    • 1970-01-01
    • 2015-06-11
    • 2017-01-08
    • 2017-03-30
    相关资源
    最近更新 更多