-1

视图.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,
    })

任务.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

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

但是在数据库添加它之后返回render_to_response

4

1 回答 1

3

您触发mail任务的调用应该是:

tasks.mail.delay()

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

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

于 2012-07-30T20:02:36.513 回答