我的视图如何返回响应并行执行某些功能

时间:2012-07-30 19:47:59

标签: django django-celery

views.py

from registration.models import Registration
from django.core.context_processors import csrf
from registration import tasks
from django.shortcuts import render_to_response
def validate(request):
    state="notvalid"
    if request.method == 'POST':# If the form has been submitted...
        form = Registration(request.POST) # A form bound to the POST data
        state="notvalid"
        if form.is_valid(): 
            username = form.cleaned_data['username']
            first_name = form.cleaned_data['first_name']
            last_name = form.cleaned_data['last_name']
            email = form.cleaned_data['email']
            password = form.cleaned_data['password']
            from django.contrib.auth.models import User
            user = User.objects.create_user(username,email,password)
            user.first_name=first_name
            user.last_name=last_name        
            user.save() 
            state="added data"
        tasks.mail()
    else:
        form = Registration() # An unbound form

    return render_to_response('auth1.html', {
        'form': form,'state':state,
    })

tasks.py

from celery import task
import celery

@celery.task()
def mail():
    from django.core.mail import send_mail
    for x in range(10000000):
        print x
    return True

必须在不影响视图响应时间的情况下执行parrelel任务。即 在后台它必须运行邮件功能

但是在数据库添加后,它需要返回render_to_response

1 个答案:

答案 0 :(得分:3)

您触发mail任务的电话应该是:

tasks.mail.delay()

如果没有delay(),任务将在与视图相同的进程中运行,而不是在Celery工作程序中运行,因此视图函数将阻塞,直到mail完成。

有关详情,请参阅http://docs.celeryproject.org/en/latest/django/first-steps-with-django.html#calling-our-task