一百四十七:CMS系统之celery实现邮件和短信异步发送

 

celery工作原理

celery官方文档:https://docs.celeryproject.org/en/latest/

安装:pip install celery

windows下还需安装eventlet来做任务调度:pip install eventlet

启动redis,已将redis密码设为为123456

简单示例

import time
from celery import Celery

celery = Celery('tasks',
broker='redis://:123456@192.168.223.128:6379/0',
backend='redis://:123456@192.168.223.128:6379/0')


@celery.task
def send_email():
print('邮件开始发送...')
time.sleep(2)
print('邮件发送结束...')

执行命令监控命令:celery -A tasks.celery --pool=eventlet worker --loglevel=info

运行发邮件操作

 

实现异步发送邮件和短信验证码

flask推荐的使用celery的方法:https://flask.palletsprojects.com/en/1.0.x/patterns/celery/

config中配置信息

CELERY_RESULT_BACKEND = 'redis://:123456@192..128:6379/0'
CELERY_BROKER_URL = 'redis://:123456@192..128:6379/0'

task代码

from celery import Celery
from flask_mail import Message
from exts import mail
import config
# 防止循环引用,在这里创建一个独立的app
from flask import Flask

app = Flask(__name__)
app.config.from_object(config)
mail.init_app(app)


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)

class ContextTask(celery.Task):
def __call__(self, *args, **kwargs):
with app.app_context():
return self.run(*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)

执行监听:celery -A tasks.celery --pool=solo worker --loglevel=info

在发邮件的地方改为异步

执行修改

 

 

短信验证码

 

关于运行监听命令:

win:celery -A tasks.celery --pool=solo worker --loglevel=info

linux:celery -A tasks.celery worker --loglevel=info

 

posted @ 2019-12-05 22:08  向前走。  阅读(611)  评论(1编辑  收藏  举报