Celery and Django simple example

Deadly 提交于 2019-11-29 19:26:53

Assuming you have both Python's celery and django-celery installed, create the following tasks.py file under your app:

utils/tasks.py

from celery import task
# other imports

@task()
def create_user(data):
    user = User.objects.create_user(
        username=data['username'], email=None, password=data['password']
    )
    user.save()
    profile = UserProfile()
    profile.user = user
    profile.token = generate_token()
    profile.save()

    return None

Delete your utils/utilities.py file in your example above.

In your code in views.py change the create_user call from:

create_user(form.cleaned_data)

to:

create_user.delay(form.cleaned_data)

Basically create_user is now a celery task; if you have the right Python packages installed (as mentioned above), code-wise (the implementation you ask for) that's it. delay executes your function asynchronously - i.e. the HTTP response is returned without waiting for the asynchronous task to complete.

Locally you can run a celery daemon process using python manage.py celeryd.

In production you have to set up the celery process itself using for instance upstart, supervisor or any other tool to control the lifecycle of such process.

Further details documented here.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!