Search code examples
djangoasynchronouscelerytask-queuebackground-task

Job completing in Celery terminal but `task.ready()` returns false (Django)


I have the following task in celery:

@shared_task
def convert_to(audio_file_pk):
     file_obj = AudioFile.objects.get(pk=audio_file_pk)
     print("Tsk Run: Returning {}".format(file_obj.audio_file.path))
     return(file_obj.audio_file.path)

I have the following in my home view where files are uploaded:

def model_form_upload(request, pk=None):
    if request.method == 'POST':
        form = AudioForm(request.POST, request.FILES)
        if form.is_valid():
            obj = form.save()
            task = convert_to.apply_async(args=[obj.pk])
            return render(request, 'index.html', {
            'form': form, 'task_id' : task.task_id
            })
            #return redirect('home', args=[obj.pk])
    else:
        form = AudioForm()
        return render(request, 'index.html', {
        'form': form
        })

I have the following code in my Ajax View:

def ajax_view(request, task_id):
    results = convert_to.AsyncResult(task_id)
    print(results.ready())
    print(task_id)
    if results.ready():
        return render_to_response('download_ready.html',
                                  {'results': results.get()})
    return render_to_response('not_ready.html', {})

This is in my urls.py

url(r'^result/(?P<task_id>.*)$', views.ajax_view, name='result')

This is the result of my task in celery:

[2017-12-16 09:08:38,534: INFO/MainProcess] Received task: nightcore.tasks.convert_to_nightcore[cd1b19fd-f721-4fa1-b9db-1ce01738d030]  
[2017-12-16 09:08:38,536: INFO/ForkPoolWorker-2] Task nightcore.tasks.convert_to_nightcore[cd1b19fd-f721-4fa1-b9db-1ce01738d030] succeeded in 0.00173856299989s: '/home/student/PycharmProjects/tonightcore/media/uploads/The_Skeptic_in_the_Room-OPs_j1EEplI_3O4k7JT.mp3'

The task prints out the value it is supposed to print.

The print(results.ready()) prints False

This is the printed out value of print(task_id) in my Ajax View:

[16/Dec/2017 09:11:19] "GET /result/cd1b19fd-f721-4fa1-b9db-1ce01738d030 HTTP/1.1" 200 22
cd1b19fd-f721-4fa1-b9db-1ce01738d030

As you can see the values are the same, but when I query http://127.0.0.1:8000/result/cd1b19fd-f721-4fa1-b9db-1ce01738d030, it returns the not_ready.html while it is supposed to return download_ready.html


Solution

  • There seem to be many others facing this problem on SO without any answers or solution.

    I found the solution here.

    https://github.com/celery/celery/issues/3675

    I uninstalled librabbitmq

    $ # call this command many times, until it says it's not installed
    $ pip uninstall librabbitmq
    

    Then changed the broker to pyamqp

    CELERY_BROKER_URL = 'pyamqp://localhost'
    

    This fixed it. Now I can get the result.