result.ready()在django芹菜中没有按预期工作?

时间:2013-02-25 08:39:44

标签: django django-celery celery-task djcelery

我有一个django芹菜视图,它执行某项任务,并在任务完成后成功写入数据库。

我这样做:

result = file.delay(password, source12, destination)

 if result.successful() is True:
      #writes into database

但是在任务完成执行后,它没有进入if条件。我尝试了result.ready()但没有运气。

修改:以上行位于同一视图中:

def sync(request):
    """Sync the files into the server with the progress bar"""
    choice = request.POST.getlist('choice_transfer')
    for i in choice:
        source12 = source + '/' + i 
        start_date1 = datetime.datetime.utcnow().replace(tzinfo=utc)
        start_date = start_date1.strftime("%B %d, %Y, %H:%M%p")

        basename = os.path.basename(source12) #Get file_name
        extension = basename.split('.')[1] #Get the file_extension
        fullname = os.path.join(destination, i) #Get the file_full_size to calculate size

        result = file.delay(password, source12, destination)

        if result.successful() is True:
             #Write into database

E:             #Writes to database

1 个答案:

答案 0 :(得分:1)

  1. 当您致电file.delay时,芹菜会将任务排队,以便稍后在后台运行。

  2. 如果您立即检查result.successful(),那么它将是错误的,因为任务尚未运行。

  3. 如果您需要链接任务(一个接一个地开火),请使用Celery的工作流程解决方案(在本例中为chain):

    def do_this(password, source12, destination):
        chain = file.s(password, source12, destination) | save_to_database.s()
        chain()
    
    
    @celery.task()
    def file(password, source12, destination):
        foo = password
        return foo
    
    
    @celery.task()
    def save_to_database(foo):
        Foo.objects.create(result=foo)