[Fixed]-Why does celery return a KeyError when executing my task?

8πŸ‘

In the celery output, you see that the task that gets picked up is

tournaments.tasks.notify_match_creation (#1)

and in your key error it is

KeyError: 'apps.tournaments.tasks.notify_match_creation'

before you call the celery task, make sure that it is imported with the same name (structure) as it is in the celery task that gets picked up (#1). Please refer to the link from celery docs for getting your relative imports rights.

one possible solution, when you launch celery – try

celery worker -A apps.tournaments.tasks.notify_match_creation

this could align your task names

πŸ‘€Shankar ARUL

0πŸ‘

I had the exact same issue, however, the following worked for me,

in my tasks.py I changed from

from celery.task import task

@task(name="generate_and_email_membership_invoice")
def my_task_name():
      ...

to

from ..celeryconf import app # the file where you have app.autodiscover_tasks()

@app.task()
def my_task_name():
     ..
πŸ‘€Dr Manhattan

0πŸ‘

Instead of using task.nameoftask it is rather a relative import as like

app.task.nameoftask
πŸ‘€Immanuel

0πŸ‘

I got the similar KeyError below for celery worker:

Traceback (most recent call last):
  File "C:\Users\kai\AppData\Local\Programs\Python\Python39\lib\site-packages\celery\worker\consumer\consumer.py", line 591, in on_task_received
    strategy = strategies[type_]
KeyError: 'account.tasks.display'

Because I have display task in store/tasks.py as shown below:

# "store/tasks.py"

from celery import shared_task

@shared_task
def display(arg):
    return arg

Then, I used the wrong path "account.tasks.display" to use display task in store/tasks.py as shown below:

# "core/settings.py"

CELERY_BEAT_SCHEDULE = {
    "scheduled_task": {
        "task": "account.tasks.display", # Here
        "schedule": 5.0,
        "args": ["Test"],
    }
}

So to solve the error, I used the correct path "store.tasks.display" as shown below, then the error was solved:

# "core/settings.py"

CELERY_BEAT_SCHEDULE = {
    "scheduled_task": {
        "task": "store.tasks.display", # Here
        "schedule": 5.0,
        "args": ["Test"],
    }
}

Leave a comment