django、celery异步发邮件

时间:2022-05-28 09:05:08

django、celery异步发邮件


  • django自带的send_mail发邮件功能执行发邮件功能会因为网络的原因造成花费的时间过长,为了解决这个问题,可以用celery + redis代替
  • 安装包:
    • pip install celery
    • pip install redis
  • 在django的根目录下新建celery_tasks文件夹,在该文件夹下新建tasks.py:
    •  from celery import Celery
      from django.conf import settings
      from django.core.mail import send_mail app = Celery('celery_tasks.tasks', broker='redis://127.0.0.1:6379/8') @app.task
      def send_register_active_email(email, username, token):
      subject = '测试'
      message = ""
      from_email = settings.EMAIL_FROM
      recipient_list = [email]
      html_message = '<h1>欢迎{}来到测试</h1>请点击下面链接激活<br><a href="http://http://127.0.0.1:8000/user/active?token={}">点击此处激活</a>'.format(
      username, token)
      send_mail(subject, message, from_email, recipient_list, html_message=html_message)


    • 调用该方法:
    •  class Register(View):
      def get(self, request):
      return render(request, 'user/register.html') def post(self, request):
      username = request.POST.get('username', '')
      password = request.POST.get('password', '')
      email = request.POST.get('email', '') # 校验用户名是否重复
      try:
      user = User.objects.get(username=username)
      except User.DoesNotExist:
      user = None if user:
      data = {'errmsg': '用户名已存在'}
      return JsonResponse(data)
      # try:
      # user = User.objects.ger(email=email)
      # except User.DoesNotExist:
      # user = None
      # if user:
      # data = {'errmsg': '邮箱已被注册'}
      # return JsonResponse(data)
      user = User.objects.create_user(username=username, password=password, email=email)
      user.is_active = 0
      user.save() info = {'user_id': user.id}
      serializer = Serializer(settings.SECRET_KEY, 3600 * 2)
      token = serializer.dumps(info).decode() # 发邮件
      send_register_active_email.delay(email, username, token)
      return redirect(reverse('user:login'))
    • worker端配置:
      • 将django项目文件复制到另一个文件夹
      • 修改tasks.py文件,设置初始化
      •  from celery import Celery
        from django.conf import settings
        from django.core.mail import send_mail
        import os
        import django os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'dream.settings')
        django.setup() app = Celery('celery_tasks.tasks', broker='redis://127.0.0.1:6379/8') @app.task
        def send_register_active_email(email, username, token):
        subject = '测试'
        message = ""
        from_email = settings.EMAIL_FROM
        recipient_list = [email]
        html_message = '<h1>欢迎{}来到测试</h1>请点击下面链接激活<br><a href="http://127.0.0.1:8000/user/active?token={}">点击此处激活</a>'.format(
        username, token)
        send_mail(subject, message, from_email, recipient_list, html_message=html_message)
      • worker端监听
      • 进入 worker端的代码的celery_tasks目录下:
        • celery -A tasks worker -l info
        • win10下可能报错:
          • pip install eventlet
          • celery -A tasks worker -l info -P eventlet
      • 当django启动调用send_mail的时候就会将发邮件的任务交给celery执行