简体   繁体   English

如何确保 Django 模型在 Celery 任务执行之前保存?

[英]How to ensure Django model saves before Celery task execution?

I have a Django 1.11 + MySQL + Celery 4.1 project where a view creates a new user record, and then kicks off a Celery task to perform additional long-running actions in relation to it.我有一个 Django 1.11 + MySQL + Celery 4.1 项目,其中一个视图创建一个新的用户记录,然后启动一个 Celery 任务来执行与其相关的其他长时间运行的操作。

The typical problem in this case is ensuring that the user creation is committed to the database before the Celery task executes.这种情况下的典型问题是确保在 Celery 任务执行之前将用户创建提交到数据库。 Otherwise, there's a race condition, and the task may try and access a record that doesn't exit if it executes before the transaction commits.否则,会出现竞争条件,如果任务在事务提交之前执行,则该任务可能会尝试访问不会退出的记录。

The way I had learned to fix this was to always wrap the record creation in a manual transaction or atomic block, and then trigger the Celery task after that.我学会了解决这个问题的方法是始终将记录创建包装在手动事务或原子块中,然后在此之后触发 Celery 任务。 eg例如

def create_user():
    with transaction.atomic():
        user = User.objects.create(username='blah')
    mytask.apply_async(args=[user.id])

@task
def mytask(user_id):
    user = User.objects.get(id=user_id)
    do_stuff(user)

However, I still occasionally see the error DoesNotExist: User matching query does not exist in my Celery worker logs, implying my task is sometimes executing before the user record gets committed.但是,我仍然偶尔会看到错误DoesNotExist: User matching query does not exist我的Celery 工作日志DoesNotExist: User matching query does not exist ,这意味着我的任务有时会在用户记录提交之前执行。

Is this not the correct strategy or am I not implementing it correctly?这不是正确的策略还是我没有正确实施它?

I believe a post_save signal would be more appropriate for what you're trying to do: https://docs.djangoproject.com/en/1.11/ref/signals/#post-save .我相信post_save信号更适合您要执行的操作: https : post_save This signal sends a created argument as a boolean, making it easy to operate only on object creation.此信号将created参数作为布尔值发送,从而可以轻松地仅对对象创建进行操作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM