使用芹菜发送异步电子邮件不起作用

时间:2016-08-22 09:36:05

标签: python django celery django-celery

我正在努力让Django不要等到发送电子邮件。我决定用Celery来做这件事。不幸的是我无法弄清楚如何使它异步工作。

我创建了一个文件tasks.py

# -*- coding: utf-8 -*-
from __future__ import absolute_import
from .notifications import CustomerNotifications
from celery import shared_task

@shared_task
def prereservation_has_been_confirmed(reservation):
    CustomerNotifications.prereservation_has_been_confirmed(reservation)

CustomerNotifications.prereservation_has_been_confirmed(reservation)方法向客户发送电子邮件。

电子邮件发送有效,但在发送电子邮件之前仍会等待。 (视图由AJAX调用。)

你知道该怎么办吗?

修改

这就是函数的调用方式:

@csrf_exempt
def reservation_confirm(request):
    if request.method == 'POST':
        reservation_id = request.POST.get('reservation_id', False)
        reservation = get_object_or_404(dolava_models.Reservation, id=reservation_id)
        reservation.confirmed = True
        reservation.save()
        tasks.prereservation_has_been_confirmed(reservation)
        return JsonResponse({})
    raise Http404(u'...')

我尝试tasks.prereservation_has_been_confirmed.delay(reservation),但它返回该连接已被拒绝。

SETTINGS.PY - 已添加BROKER_URL = 'django://''kombu.transport.django'并已迁移。

# -*- coding: utf-8 -*-

"""
Django settings for dolava project.

Generated by 'django-admin startproject' using Django 1.9.7.

For more information on this file, see
https://docs.djangoproject.com/en/1.9/topics/settings/

For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.9/ref/settings/
"""

import os

# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))


# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/1.9/howto/deployment/checklist/

# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'secret_key'

# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True

ALLOWED_HOSTS = []


# Application definition

INSTALLED_APPS = [
    'admin_interface',
    'flat',
    'colorfield',
    'django.contrib.admin',
    'django.contrib.auth',
    # 'djcelery_email',

    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'dolava_app',
    # 'constance',

    # 'constance.backends.database',
    'solo',
    'django_extensions',
    'django_tables2',
    'django_countries',
    'kombu.transport.django'
]

MIDDLEWARE_CLASSES = [
    'django.middleware.security.SecurityMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.auth.middleware.SessionAuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',

]

ROOT_URLCONF = 'dolava.urls'

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [],
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                'django.template.context_processors.debug',
                'django.template.context_processors.request',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
                'django.core.context_processors.media',
            ],
        },
    },
]

WSGI_APPLICATION = 'dolava.wsgi.application'
BROKER_URL = 'django://'

# Database
# https://docs.djangoproject.com/en/1.9/ref/settings/#databases

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.sqlite3',
        'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
    }
}


# Password validation
# https://docs.djangoproject.com/en/1.9/ref/settings/#auth-password-validators

AUTH_PASSWORD_VALIDATORS = [
    {
        'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
    },
]


# Internationalization
# https://docs.djangoproject.com/en/1.9/topics/i18n/

LANGUAGE_CODE = 'en-us'

TIME_ZONE = 'UTC'

USE_I18N = True

USE_L10N = True

USE_TZ = True


# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/1.9/howto/static-files/

STATIC_URL = '/static/'
PROJECT_ROOT = os.path.dirname(os.path.abspath(__file__))
STATIC_ROOT = os.path.join(PROJECT_ROOT, 'static')

# CELERY_ALWAYS_EAGER = True
# SMTP SETTINGS
# EMAIL_BACKEND = 'djcelery_email.backends.CeleryEmailBackend'
EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend'
# EMAIL_BACKEND = "mailer.backend.DbBackend"
EMAIL_USE_TLS = True
EMAIL_HOST = 'smtp.gmail.com'
EMAIL_PORT = 587
EMAIL_HOST_USER = 'xxx@gmail.com'
EMAIL_HOST_PASSWORD = 'pass'




MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
MEDIA_URL = '/media/'

2 个答案:

答案 0 :(得分:2)

[评论后]您的任务已正确发送到代理(在您的情况下为数据库),您可以检查您的待处理任务是否存在。

您在控制台中看不到任何内容,因为您必须启动芹菜工作程序,该工作程序将读取代理上的所有待处理任务并执行它们。 have you started the worker process?在那里你会看到正在调用的任务以及结果或追溯(如果出现故障)

答案 1 :(得分:1)

您没有对prereservation_has_been_confirmed()进行异步调用,以便使用prereservation_has_been_confirmed.delay(...)来延迟函数执行

@csrf_exempt
def reservation_confirm(request):
    if request.method == 'POST':
        reservation_id = request.POST.get('reservation_id', False)
        reservation = get_object_or_404(dolava_models.Reservation, id=reservation_id)
        reservation.confirmed = True
        reservation.save()

        # change HERE, you are calling your function directly not asynchronously
        tasks.prereservation_has_been_confirmed(reservation)
        # change to below
        # tasks.prereservation_has_been_confirmed.delay(reservation)
        return JsonResponse({})
    raise Http404(u'...')

除此之外,您尚未正确配置Celery以在Django应用程序中使用。 见Django celery first steps