我正在运行一项任务,在第三方服务上创建一个帐户,并保存该服务对我的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
值都是正确的。
现在这里有点奇怪。我认为实际上失败的是celery任务调用运行这段代码的实用程序。如果我手动运行此实用程序,则会正确保存字段。如果我将其作为正常工作流程的一部分运行(在异步任务中调用),则会在第三方服务上创建帐户,因此我知道此代码正在执行,但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
可能是你的任务没有运行,必须抛出错误。你检查了芹菜日志吗?