Flask使用celery发送邮件和发送短信验证码

邮箱: qq邮箱

手机验证码: 云通讯手机验证码

  1. tasks.py

    from flask import Flask
    from flask_mail import Message
    
    from celery import Celery
    
    from exts import mail
    from libs.yuntongxun.sms import CCP
    import config
    
    app = Flask(__name__)
    
    app.config.from_object(config)
    
    mail.init_app(app)
    
    # 运行本文件
    # linux上
    # celery -A tasks.celery worker -l info
    # window上
    # celery -A tasks.celery worker --pool=solo -l info
    
    
    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对象
    celery = make_celery(app)
    
    
    # qq邮箱
    @celery.task
    def send_mail(subject, recipients, body):
        message = Message(
            subject=subject,
            recipients=recipients,
            body=body
        )
    
        mail.send(message)
        
    # 短信验证码的
    @celery.task
    def send_sms_captcha(telephone, captcha):
        ccp = CCP()
        ccp.send_Template_sms(telephone, [captcha, config.CAPTCHA_OUTTIME], 1)
    

    Flask使用celery发送邮件和发送短信验证码_第1张图片

  2. config.py

     # MAIL_USE_TLS: 端口号587
     # MAIL_USE_SSL: 端口号465
     # QQ不支持非加密方式发送邮箱
     # 发送者邮箱的服务器地址
     MAIL_SERVER = "smtp.qq.com"
     MAIL_PORT = "587"
     # 设置为True以后flask发送邮件旧回忆TLS协议去发送
     MAIL_USE_TLS = True
     # MAIL_USE_SSL:默认为False
     # MAIL_DEBUG:默认app.debug
     MAIL_USERNAME = "邮箱账号"
     MAIL_PASSWORD = "授权码"
     MAIL_DEFAULT_SENDER = "邮箱账号"
    
    # 短信验证码有效时间1
    CAPTCHA_OUTTIME = "1"
    
    # celery相关配置
    CELERY_RESULT_BACKEND = "redis://127.0.0.1:6379/0"
    CELERY_BROKER_URL = "redis://127.0.0.1:6379/0"
    
  3. 启动worker

    # linux上
    celery -A tasks.celery worker -l info
    # window上
    celery -A tasks.celery worker --pool=solo -l info
    
  4. 启动中间人redis

  5. 异步发送邮箱, 和短信

    # 调用函数是用了delay那么就会把该任务添加到broker 也就是 我们配置的redis中
    
    # 发送qq邮件
    send_mail.delay("Python论坛邮箱验证码", [email], "您的验证码是:%s" % captcha)
    
    # 发送手机短信验证码
    send_sms_captcha.delay(telephone, captcha)
    

你可能感兴趣的:(Python-Flask)