Send email asynchronously using redis+celery

Environment: centos7+django2+redis+celery

 

1. First install redis and celery.

pip install celery

pip intsall redis

 pip install django-redis
 

  • start service redis start | systemctl start redis
  • Edit the redis configuration file vim /etc/redis.conf
  • See redis process ps -aux | grep redis
  • Password modification method: vim .etc/redis.conf Find the sentence #requirepass foobared. Add requirepass yoursecret#your password after it. Restart rsystemctl restart redis. Of course, you can also not set

For more redis configuration, please go to the official documentation to learn. Chinese website http://www.redis.cn/ . English official website https://redis.io/

2. Create a tasks.py. [ must be this name ] under the created appa directory file .

from __future__ import absolute_import, unicode_literals
from celery import shared_task
from django.core.mail import send_mail
import logging

logger = logging.getLogger(__name__)


@shared_task
def celery_send_email(subject, message, from_email, recipient_list, **kwrags):
    try:
        # 使用celery并发处理邮件发送的任务
        logger.info("\n开始发送邮件")
        send_mail(subject, message, from_email, recipient_list, **kwrags)
        logger.info("邮件发送成功")
        return 'success!'
    except Exception as e:
        logger.error("邮件发送失败: {}".format(e))


Note: The first line is best: from __future__ import absolute_import, unicode_literals. Otherwise, it is easy to make mistakes.

3. Add the celery.py file in the same directory as setting.py.

from __future__ import absolute_import, unicode_literals
import os
from celery import Celery

# 为celery程序设置DJANGO_SETTINGS_MODULE环境变量
os.environ.setdefault('DJANGO_SETTINGS_MODULE', '你的项目名字.settings')

app = Celery('project_name')

# 从Django的设置文件中导入CELERY设置
app.config_from_object('django.conf:settings', namespace='CELERY')
# 从所有已注册的app中加载任务模块
app.autodiscover_tasks()


@app.task(bind=True)
def debug_task(self):
    print('Request: {0!r}'.format(self.request))

Fourth, find the __init__.py file in the same directory as setting.py

from __future__ import absolute_import, unicode_literals
# 这将保证celery app总能在django应用启动时启动
from .celery import app as celery_app


__all__ = ['celery_app']

Five, open the setting.py file to add

#扣扣邮箱验证
# 邮件配置
EMAIL_USE_SSL = True

EMAIL_HOST = 'smtp.qq.com'  # 如果是 163 改成 smtp.163.com
EMAIL_PORT = 465
EMAIL_HOST_USER = '[email protected]' # 你的 QQ 账号
EMAIL_HOST_PASSWORD = '' #你的授权密码。具体在设置--账号里面,一定要打开POP3服务。
# 默认邮件
DEFAULT_FROM_EMAIL = EMAIL_HOST_USER



#celery配置
CELERY_BROKER_URL = 'redis://localhost:6379' #celery中间人 redis://redis服务所在的ip地址:端口/数据库号
CELERY_RESULT_BACKEND = 'redis://localhost:6379'#celery结果返回,可用于跟踪结果
#celery内容等消息的格式设置
#: Only add pickle to this list if your broker is secured
CELERY_ACCEPT_CONTENT = ['json']
CELERY_TASK_SERIALIZER = 'json'
CELERY_ENABLE_UTC = True
#celery时区设置,使用settings中TIME_ZONE同样的时区
CELERY_TIMEZONE = 'Asia/Shanghai'

6. Add a view file to the views.py file


from django.http import HttpResponse
from your_product import setting
from celery_test.tasks import celery_send_email<br><br>
def add_task_to_celery(request):
    email = ''#需要发送邮件的邮箱地址
    celery_send_email.delay(u'邮件主题', '邮箱内容', setting.DEFAULT_FROM_EMAIL, [email])
    return HttpResponse('hello world')

7. Add a route for sending emails in the url.py file

from django.contrib import admin
from django.urls import path
from your_urls import views  #导入你的视图文件路径
 
urlpatterns = [
    path('admin/', admin.site.urls),
    path('send_email/', views.add_task_to_celery, name='send_email'),
]

8. Execute the following command in the same level directory of manage.py to start the worker process of celery (mainly used for consumption or task execution)

celery -A your_projectName  worker --loglevel=info

Reference blog:

https://www.cnblogs.com/wumingxiaoyao/p/8515075.html

https://blog.csdn.net/qq_32868151/article/details/78937719

https://blog.csdn.net/xiaohuoche175/article/details/81480576

Guess you like

Origin blog.csdn.net/hard_days/article/details/103254622