Celery

安装:

pip install celery 

步骤:

第一步:选一个broker
711.png

第二步:定义一个task
Celery_第1张图片
屏幕快照 2030.png

第三步:开启worker


31.png

第四步:调用test方法
Celery_第2张图片
21.png

celery发送邮件

ext.py
from flask_cache import Cache
from flask_mail import Mail
from flask_migrate import Migrate
from flask_sqlalchemy import SQLAlchemy

db = SQLAlchemy()
mail = Mail()
cache = Cache(config={'CACHE_TYPE': 'redis'})

my_celery = Celery(__name__,borker='/redis:localhost:6379/')

@my_celery.task
def send_mail(email,username,url):
      #只能从这里导入 不然则 循环导入
       from App import create_app
       app = create_app()
       with app.app_context():
              
        # 1. 创建一个Message对象
        message = Message()
    
        # 2. 配置Message
        # 2.1 拿到post提交时填写的邮箱地址
        message.recipients = [email]
        # 2.2 设置邮箱的主题
        message.subject = '欢迎注册1024网'
        # 2.3 设置邮箱的内容
        # http://127.0.0.1:5000/accounts/?token=
       
        message.html = render_template('ActivatePage.html', username=username,
                                       activate_url=url)
        # 2.4 设置发送者。如果在settings里设置里MAIL_DEFAULT_SENDER配置项,可以不再设置sender属性
        # message.sender = '[email protected]'
    
        # 3. 把Message对象发出去
        mail.send(message)

def init_ext(app):
    db.init_app(app=app)
    Migrate(app=app, db=db)
    mail.init_app(app=app)
    cache.init_app(app=app)

UserAPI.py

import uuid

from flask import render_template, url_for
from flask_mail import Message
from flask_restful import Resource, reqparse, fields, marshal, marshal_with
from werkzeug.security import generate_password_hash

from App.ext import db, mail, cache
from App.models import User

parser = reqparse.RequestParser()

parser.add_argument('username', required=True, help='缺少用户名')
parser.add_argument('password', required=True, help='缺少密码')
parser.add_argument('email', required=True, help='缺少邮箱')

user_fields = {
    'user_name': fields.String,
    'e_mail': fields.String,
    '是否激活': fields.Boolean(attribute='is_activity')
}
result_fields = {
    'msg': fields.String,
    'status': fields.Integer,
    'data': fields.Nested(user_fields)
}

test_fields = {
    'result': fields.String,
    'hi': fields.String
}


class UerResource(Resource):
    @marshal_with(test_fields)
    def get(self):
        # url = url_for('accountresource', _external=True, token='dfasdfk')
        # print(url)

        return {'result': 'hello', 'sss': 'mmmm'}
    
    def post(self):
        args = parser.parse_args()
    
        username = args.get('username')
        password = args.get('password')
        email = args.get('email')
        # 根据用户名生成一个HASH值
        token = str(uuid.uuid5(uuid.NAMESPACE_DNS, username))
    
        user = User()
        user.user_name = username
        user.password = generate_password_hash(password)
        user.e_mail = email
        user.token = token
    
        # save里有异常的处理机制
        msg = user.save()
    
        # 如果有异常,直接返回
        if msg.get('error'):
            return msg
    
        # 用户写入数据库成功
        cache.set(token, user.id, timeout=60)
    
        # 发送激活邮件
         url = url_for('accountresource', _external=True, token=token)
         send_mail.delay(email,username,url)
    
        # return {'msg': '注册成功', 'status': 201, 'data': user}
        return marshal({'msg': '注册成功', 'status': 201, 'data': user}, result_fields)

启动命令

celery -A App.ext:my_celery worker --loglevel=info

你可能感兴趣的:(Celery)