之前在項目中我們發送郵件和 短信都是阻塞的,現在我們來利用Celery來優化它們
官方使用文檔: http://flask.pocoo.org/docs/1.0/patterns/celery/
redis服務器及插件,還有cerely在上節我們已經安裝好,這里就不重復過程了。
首先,來完成郵件
在項目下新建tasks.py
from flask import Flask import config from celery import Celery from flask_mail import Message from exts import mail ##這里沒有直接使用from bbs import app,是因為會出現循環引用的問題 app = Flask(__name__) app.config.from_object(config) mail.init_app(app) #在配置文件需要配置CELERY_RESULT_BACKEND、CELERY_BROKER_UR def make_celery(app): celery = Celery(app.import_name, backend=app.config['CELERY_RESULT_BACKEND'], broker=app.config['CELERY_BROKER_URL']) celery.conf.update(app.config) TaskBase = celery.Task class ContextTask(TaskBase): abstract = True def __call__(self, *args, **kwargs): with app.app_context(): return TaskBase.__call__(self, *args, **kwargs) celery.Task = ContextTask return celery celery = make_celery(app) @celery.task def send_mail(subject,recipients,body): message = Message(subject=subject,recipients=recipients,body=body) mail.send(message)
編輯config.py
# Celery相關配置 CELERY_RESULT_BACKEND = "redis://10.2.2.120:6379/0" CELERY_BROKER_URL = "redis://10.2.2.120:6379/0"
編輯cms.views.py發送郵件的部分
在項目目錄下啟動worker
celery -A tasks.celery --pool=eventlet worker --loglevel=info
啟動項目,測試修改郵箱成功!
完成短信優化
編輯tasks.py
.. from utils.aliyunsms.send_sms import send_sms @celery.task def send_mail(subject,recipients,body): message = Message(subject=subject,recipients=recipients,body=body) mail.send(message)
編輯common.virews.py
重啟下worker
注冊頁測試手機獲取驗證碼