a.Celery其實是生產者消費者模型來實現異步的:
python
b.實驗所需組件:
1) Django
2) Celery
3) Redisredis
2.實驗代碼
a.啓動redis-serverdjango
#./redis-server /etc/redis/redis.conf #cat /etc/redis/redis.conf bind 192.168.60.72 port 6379 daemonize yes dbfilename dump.rdb dir /var/lib/redis logfile "/var/log/redis/redis-server.log" #ss -antlp | grep 6379 LISTEN 0 128 192.168.60.72:6379 *:* users:(("redis-server",pid=77880,fd=6))
b.配置Djangowindows
#django-admin startproject send_mail_prj #cd send_mail_prj #django-admin startapp app01 建立Celery相關文件: ├─manage.py │ ├─app01 │ │ admin.py │ │ apps.py │ │ models.py │ │ tests.py │ │ urls.py │ │ utils.py │ │ views.py │ ├─__init__.py │ ├─celery_tasks //建立以下文件 │ │ config.py │ │ main.py │ │ __init__.py │ │ │ ├─sms │ │ tasks.py │ └─__init__.py │ │ └─send_mail_prj │ asgi.py │ settings.py │ urls.py │ wsgi.py │─ __init__.py
#celery_tasks.init.py爲空服務器
#celery_tasks.config.py併發
# Celery 配置文件 broker_url = 'redis://192.168.60.72/10'
#celery_tasks.main.pyapp
# celery入口 from celery import Celery # 初始化celery實例 celery_app = Celery('send_mail') # 加載celery配置 celery_app.config_from_object('celery_tasks.config') # 註冊任務 celery_app.autodiscover_tasks(['celery_tasks.sms'])
#celery_tasks.sms.init.py 爲空異步
#celery_tasks.sms.tasks.pyide
from celery_tasks.main import celery_app from email.mime.text import MIMEText import smtplib # 定義異步任務 @celery_app.task(name='send_mail') def sendEmail(): # 設置服務器所需信息 # 163郵箱服務器地址 mail_host = 'smtp.163.com' # 163用戶名 mail_user = 'yxxxx5' # 密碼(部分郵箱爲受權碼) mail_pass = 'KIMxxxxxxxxxxxZ' # 郵件發送方郵箱地址 sender = 'yxxxx5@163.com' # 郵件接受方郵箱地址,注意須要[]包裹,這意味着你能夠寫多個郵件地址羣發 receivers = ['yxxxx5@163.com'] # 設置email信息 # 郵件內容設置 message = MIMEText('dear frank, sdfsdfsdfasfdsdfsfwetrwre', 'plain', 'utf-8') # 郵件主題 message['Subject'] = 'hi fxxxg sir sdfsfsdfasf' # 發送方信息 message['From'] = sender # 接受方信息 message['To'] = receivers[0] # 登陸併發送郵件 try: smtpObj = smtplib.SMTP() # 鏈接到服務器 smtpObj.connect(mail_host, 25) # 登陸到服務器 smtpObj.login(mail_user, mail_pass) # 發送 smtpObj.sendmail( sender, receivers, message.as_string()) # 退出 smtpObj.quit() return ('success') except smtplib.SMTPException as e: print('error', e) # 打印錯誤
3.Django寫視圖函數和配置URL
#app01.views.py函數
from django.http import HttpRequest, HttpResponse # 導入異步任務 from celery_tasks.sms.tasks import sendEmail # Create your views here. def register(request): # 發送郵件 sendEmail.delay() return HttpResponse('hello')
#app01.urls.py
from django.conf.urls import url from . import views urlpatterns = [ url(r'register/$', views.register, name='register'), ]
#send_mail_prj.urls.py
from django.contrib import admin from django.urls import path from django.conf.urls import url, include urlpatterns = [ path('admin/', admin.site.urls), url(r'^', include('app01.urls')), ]
4.啓動Celery
#cd send_mail_prj
#celery -A celery_tasks.main worker -l info
#celery -A celery_tasks.main worker -l info -P eventlet //windows下面須要添加-P eventlet
5.啓動django
#cd send_mail_prj
#python manage.py runserver 0.0.0.0:80
6.訪問127.0.0.1/register/
實驗完成。