我正在尝试添加一个长时间运行的异步任务,并让它每隔一段时间更新一次进度状态。我使用了Django-rest-framework服务器,RabbitMQ代理,Celery worker。我可以在Celery中添加任务,甚至可以在任务完成后成功地检索结果。
然而,每当我尝试在任务完成之前获取状态时,我都会得到以下结果:
任务结果=无,任务状态=待定,task.info =无
尝试获取状态后完成时:
任务结果=无,任务状态=待定,task.info =无
DeployML/
manage.py
DeployML/
...
settings.py
tasks.py
dcelery.py
views.py
urls.py
dcelery.py:
import os
from celery import Celery
import sys
sys.path.append('.....DeployML')
sys.path.append('.....DeployML/DeployML')
# Set the default Django settings module for the 'celery' program.
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'DeployML.settings')
app = Celery('DeployML', backend='rpc://', broker='pyamqp://guest@localhost//', worker_state_db = '/tmp/celery_state')
app.config_from_object('django.conf:settings')
app.autodiscover_tasks()
@app.task(bind=True)
def debug_task(self):
print(f'Request: {self.request!r}')
tasks.py:
import os
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'DeployML.settings')
from celery import shared_task
from celery import current_task
from dcelery import app
import time
@app.task(bind=True)
def addShrd(self, x, y):
for i in range(4):
time.sleep(5)
progress_percent = i
#NOTE update_state not working yet
current_task.update_state(state='PROGRESS', meta={'current': i, 'total': 4})
return x + y
views.py:
# ...
# ...
@api_view(['GET', 'POST'])
def celer_view(request):
print("authentication: ", request.user, request.auth)
if request.method == 'GET':
result = addShrd.delay(17,10)
return Response({'task_id': str(result.id)})
elif request.method == 'POST':
return Response({'some': 'POST response data'})
return Response({'some': 'data'})
from celery.result import AsyncResult
@api_view(['GET', 'POST'])
def poll_state(request):
data = 'Fail'
print("requ: "+str(request.POST.get('task_id')))
if 'task_id' in request.POST.keys() and request.POST['task_id']:
task_id = request.POST['task_id']
task = AsyncResult(task_id)
print("meta data: "+ str(task.info))
data = str(task.result) + " " +str(task.state) + " | " + str(task.info)
else:
data = 'No task_id in the request'
return Response({'some': 'poll_state data: '+data})
编辑:我已经更新了views.py poll_state方法以使用celery.result.AsyncResult,而之前我使用的是dcelery. AsyncResult。但是这并没有解决这个问题。
EDIT 2:这个问题现在已经解决了。我发现在执行update_state和AsyncResult之间有几秒钟的延迟。由于我的任务运行时间不长(只有20秒),在RabbitMQ可以保存中间进度之前,任务已经完成。但是,如果我增加任务运行时间到100秒,我可以看到中间结果。
1条答案
按热度按时间tyky79it1#
checkout 异步结果
还可以在此处检查用法:celery.result.AsyncResult usages