Celery是一个分布式任务队列,它可以让你异步处理任务,例如发送邮件、图片处理、数据分析等。
在项目中和celery 有关系的文件如下:
task.py : 创建celery.py 对象,并且添加任务,和app绑定,注意:这里没有将celery放在app.py 文件中绑定,是为了防止出现循环引用的问题。
views.py: 调用celery 中的任务。
需要在config.py 中配置:
# celery 相关配置
CELERY_RESULT_BACKEND = 'redis://127.0.0.1:6379/0'
CELERY_BROKER_URL = 'redis://127.0.0.1:6379/0'
# 邮箱配置信息
# MAIL_USE_TLS 端口号是587
# MAIL_USE_SSL 端口号是465
# QQ邮箱不支持非加密方式发送邮件
MAIL_SERVER = 'smtp.qq.com'
MAIL_USE_TLS = True
MAIL_PORT = 587
MAIL_USERNAME = "你的邮箱地址"
MAIL_PASSWORD = "你的邮箱密钥"
MAIL_DEFAULT_SENDER = "你的邮箱地址"
注意:我这里使用的是qq邮箱的配置,需要在邮箱的账号与安全里面去生成授权码
task.py 代码如下:
from celery import Celery
from flask import Flask
from flask_mail import Mail, Message
from exts import mail
import configapp = 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)TaskBase = celery.Taskclass ContextTask(TaskBase):abstract = Truedef __call__(self, *args, **kwargs):with app.app_context():return TaskBase.__call__(self, *args, **kwargs)celery.Task = ContextTaskreturn celerycelery = make_celery(app)@celery.task
def send_mail(subject, recipients, body):message = Message(subject=subject, recipients=recipients, body=body)mail.send(message)
views.py :
import random
import stringfrom flask import Blueprint, render_template, request, jsonify
from task import send_emailbp = Blueprint('front', __name__, url_prefix='/')@bp.route('/email/captcha/', methods=['GET'])
def email_captcha():email = request.args.get('email')sample = string.digits + string.ascii_lowercasecaptcha = "".join(random.sample(sample, 4))if email:send_email.delay(subject='CMS论坛邮箱修改', recipients=[email], body=captcha)return jsonify({"code": 200, "message": "获取验证码成功!", "data": captcha})else:return jsonify({"code": 400, "message": "获取验证码失败!", "data": None})
在页面中访问:http://127.0.0.1:5000/email/captcha/?email=你要发送的邮箱地址 就可以测试发送邮箱验证码。
发送验证码之前一定要启动redis!!!
页面输出的结果是:
{"code": 200,"data": "p2fv","message": "\u83b7\u53d6\u9a8c\u8bc1\u7801\u6210\u529f\uff01" }
监听celery:在终端输入 celery -A task.celery worker --pool=solo --loglevel=info