Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django, ImportError: cannot import name 'task' from 'celery'

I have Django application that was using Celery version 4.4.2, which was working fine.

from celery import task
import logging


@task(ignore_result=True)
def log_user_activity(user_id):
    try:
        logging.info(user_id)
    except Exception as e:
        logging.error(str(e))

As I tried to update the Celery version to v5.2.2 I get below error:

ImportError: cannot import name 'task' from 'celery'

Can someone help what is task been replaced with? they still have example here with same. https://github.com/celery/celery/blob/v5.2.2/examples/celery_http_gateway/tasks.py

like image 605
Avi Avatar asked Mar 20 '26 01:03

Avi


2 Answers

This API was deprecated, and then removed in 5.0.

That page suggests to change

from celery import task

into

from celery import shared_task

There are other changes as well which don't apply to the snippet you've posted but may apply to the rest of your code. See that page (and the rest of the documentation, especially the Upgrading from Celery 4.x section) for more details.

like image 200
Wander Nauta Avatar answered Mar 22 '26 13:03

Wander Nauta


Some older things are deprecated in Celery 5.0 and The latest version of the celery is working fine and most of the new things are added in the new version. Recommended: you need to use the latest version of the celery.

celery.py

from celery import Celery
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'pj_name.settings')
app = Celery('pj_name')
app.config_from_object('django.conf:settings', namespace='CELERY')
app.autodiscover_tasks()

after that go under the app/tasks.py and add your first scheduler function.

from pj_name.celery import app
@app.task
def first_task():
    pass

the above code block is worked if you are using celery latest version.

like image 23
Deepak Kumar Avatar answered Mar 22 '26 13:03

Deepak Kumar



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!