1. 安裝 2. 項目目錄 3. settings配置 4. celery模塊 python 在task文件中 from __future__ import absolute_import, unicode_literals import os from celery import Celery s ...
安裝
pip install django==1.11.7 pip install celery
項目目錄
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
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 = '[email protected]' EMAIL_HOST_PASSWORD = '**********' DEFAULT_FROM_EMAIL = 'sam <[email protected]>'
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))
App下的init文件
from __future__ import absolute_import, unicode_literals from task import app as celery_app __all__ = ['celery_app']
發送郵件
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')
發送郵件調用
send_register_mail.delay(username, email, token)
開啟任務隊列
celery -A task worker -l info 或者 celery -A task worker --loglevel=info