简体   繁体   中英

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

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM