Flask实战第67天:Flask+Celery实现邮件和短信异步发送

之前在项目中我们发送邮件和 短信都是阻塞的,现在我们来利用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

注册页测试手机获取验证码

猜你喜欢

转载自www.cnblogs.com/sellsa/p/9757905.html
今日推荐