简体   繁体   中英

calling celery task with delay gets stuck

A celery task defined like:

from celery.decorators import task

@task(name="send_email")
def send_email(email, host):

When calling it like this, Django gets stuck:

send_email.delay(email, host)

Like if it wasnt being ran asynchronously,

what am I missing?

Those are some of the celery settings, and its using redis as broker:

>>> settings.CELERY_ACCEPT_CONTENT
[u'application/json']
>>> settings.CELERY_BROKER_URL
u'redis://redis:6379/0'
>>> settings.CELERY_RESULT_BACKEND
u'redis://redis:6379/0'
>>> settings.CELERY_RESULT_SERIALIZER
u'json'
>>>

I'd rather comment but I need 50 rep first, but we need the rest of the function. It's impossible to fix unless you show us all that you're doing. Because you didn't show it, I'll show you one of mine, and hopefully it will give you some clarity on what you're doing wrong. I have a few celery email functions, but they only take 1 argument (an id from the object), and return the value to the function that called it. Note that you will also need to have your settings.py contain the proper EMAIL_BACKEND, etc settings (like EMAIL_HOST, and so on).

But if you're only using the console, the only email setting you'd need is EMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend' . The following example works with this as long as you have celery running, and everything pointing to the right places.

Example:

Assume the models, etc were imported correctly so the linter shows no errors, and this is all in one file.

@task
def order_created(order_id):
    """Task to send an email notification when an order is successfully created"""
    order = Order.objects.get(id=order_id)
    subject = 'Order number {}'.format(order.id)
    message = 'Dear {},\n\nYou have successfully made an order. Your order id is {}.'.format(order.first_name, order.id)
    mail_sent = send_mail(subject, message, 'you@your_email.com', [order.email])
    return mail_sent



def make_an_order(request):
    cart = Cart(request)
    if request.method == 'POST':
        form = OrderCreateForm(request.POST)
        if form.is_valid():
            order = form.save()
            for item in cart:
                OrderItem.objects.create(order=order, product=item['product'], price=item['price'], quantity=item['quantity'])
            cart.clear()
            order_created.delay(order.id)    # id is passed to celery function
            request.session['order_id'] = order.id
            return redirect(reverse('payment_app:process'))
    else:
        form = OrderCreateForm()  # instantiates form based on Order model.
        return render(request, 'orders_app/create.html', {'cart': cart, 'form': form})

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