Django+Celery非同步傳送郵件

Sajinchang發表於2018-12-24
  1. 安裝

    pip install django==1.11.7
    pip install celery
  2. 專案目錄

     AXF
        ├── alipay_config
        │   ├── alipay_rsa_public_key.pem
        │   └── app_rsa_private_key.pem
        ├── App
        │   ├── admin.py
        │   ├── apps.py
        │   ├── __init__.py
        │   ├── migrations
        │   │   ├── __init__.py
        │   │   └── __pycache__
        │   ├── models.py
        │   ├── __pycache__
        │   ├── tests.py
        │   ├── urls.py
        │   ├── views_contstant.py               封裝傳送郵件函式
        │   └── views.py
        ├── AXF
        │   ├── __init__.py
        │   ├── __pycache__
        │   ├── settings.py
        │   ├── urls.py
        │   └── wsgi.py
        ├── task.py                              celery非同步任務                          
        ├── manage.py
        ├── middleware
        ├── static
    
  3. settings配置

    #email
    EMAIL_BACKEND = `django.core.mail.backends.smtp.EmailBackend`
    EMAIL_USE_TLS = False
    EMAIL_USE_SSL = True
    EMAIL_HOST = `smtp.163.com`
    EMAIL_PORT = 465
    EMAIL_HOST_USER = `sajinde@163.com`
    EMAIL_HOST_PASSWORD = `**********`
    DEFAULT_FROM_EMAIL = `sam <sajinde@163.com>`
  4. celery模組

    #在task檔案中
    
    
    from __future__ import absolute_import, unicode_literals
    import os
    
    from celery import Celery
    
    # set the default Django settings module for the `celery` program.
    #        AXF.settings:專案下的settings檔案
    os.environ.setdefault(`DJANGO_SETTINGS_MODULE`, `AXF.settings`)
    
    
    broker = `redis://127.0.0.1:6379/6`  # 將要進行的任務
    backend = `redis://127.0.0.1:6379/7` # 返回的結果
    app = Celery(`App`, broker=broker, backend=backend)
    # app = Celery(`App`)
    
    # Using a string here means the worker doesn`t have to serialize
    # the configuration object to child processes.
    # - namespace=`CELERY` means all celery-related configuration keys
    #   should have a `CELERY_` prefix.
    # app.config_from_object(`django.conf:settings`, namespace=`CELERY`)
    
    # Load task modules from all registered Django app configs.
    app.autodiscover_tasks()     #自動搜尋所有的任務
    
    `debug開啟`
    # @app.task(bind=True)
    # def debug_task(self):
    #     print(`Request: {0!r}`.format(self.request))
  5. App下的init檔案

    from __future__ import absolute_import, unicode_literals
    from task import app as celery_app
    
    __all__ = [`celery_app`]
  6. 傳送郵件

    from celery import shared_task
    
    @shared_task     #可多次重用,@shared_task裝飾可以讓你無需任何具體的應用程式例項建立任務
    def send_register_mail(username, email, token):
        # 傳送郵件
        print(`------------------------------------`)
        sleep(10)
        print(`------------------------------------`)
        title = `啟用`
        msg = ` `
    
        data = {
            `username`: username,
            `url`: `http://127.0.0.1:8000/app/active/?token=` + token
        }
        temp = loader.get_template(`user/active.html`)
        html = temp.render(data)
    
        receiver = [
            email,
        ]
    
        send_mail(title,
                  msg,
                  from_email=settings.DEFAULT_FROM_EMAIL,
                  recipient_list=receiver,
                  html_message=html)
    
        print(`send mail`)
  7. 傳送郵件呼叫

    send_register_mail.delay(username, email, token)
  8. 開啟任務佇列

    celery -A task worker -l info        或者
    celery -A task worker --loglevel=info

相關文章