无法将响应数据保存到实例的字段;同一块中的其他数据正确保存(Django/Celery)



我正在运行一个任务,以在第三方服务上创建一个帐户,并从该服务对我的profile对象的响应中保存相关数据。任务正在运行,数据正确返回,但不能正确保存在对象上。

相关代码:

    # payload is generated in helper method. if that was the point of
    # failure, i'd see an error
    result = self.third_party_client.post(self.creation_endpoint, payload)
    json_result = result.json()
    if json_result.get('Error') != 'SUCCESS':
        # Account Creation Failed. error is handled.
    else:
        # Currently I log this on our staging server to make sure
        # the data's coming back properly; it is returned as expected
        self.logger.error('CoreCard Account Created. Data: {}'.format(json_result))
        profile = user.profile
        profile.account_number = json_result.get('AccountNumber')
        profile.card_number_last_four = int(json_result.get('CardNumber')[12:])
        profile.customer_id = json_result.get('CustomerID')
        profile.account_creation_datetime = datetime.datetime.utcnow()
        profile.save()

因此,如果我然后查询此profile实例,它具有预期的account_creation_datetime值,但其他字段为空白。我已经检查了日志,json_result值都正确。

现在这有点奇怪。我认为实际上失败的地方是芹菜任务,该任务称为运行该代码的实用程序。如果我手动运行此实用程序,则将正确保存该字段。如果我作为正常工作流程的一部分(在异步任务中调用)运行,则该帐户是在第三方服务上创建的,因此我知道此代码正在执行,但是profile字段(account_creation_datetime除外)是空白的。该任务看起来像这样:

@shared_task(bind=True, max_retries=3)
def create_account_task(self, guid):
    profile = Profile.objects.get(historical_id=guid)
    profile.account_creation_worker_id = current_task.request.id # Per http://docs.celeryproject.org/en/latest/reference/celery.html#celery.current_task
    profile.save()
    # Sanity Check
    if profile.approval_date is not None:
        util = CoreCardUtility()
        util.create_corecard_account(profile.user)
        return True
    return False

在此工作流中,即使我知道任务运行,profile.account_creation_worker_id也是也无法正确保存,因为该帐户是在第三方服务上创建的。

我有点损失 - 我在这里缺少的芹菜工人或线程是否存在问题?

谢谢您的帮助!

获取任务ID(对于2.2.0以上的芹菜版本),

profile.account_creation_worker_id = create_account_task.request.id

而不是

profile.account_creation_worker_id = current_task.request.id

可能,您的任务没有运行,必须丢弃错误。您检查了芹菜日志吗?

最新更新