flask中使用celery1--简单实例
之前的博客
之前写过一篇celery的博客:任务分发系统Celery
简单的demo代码
项目结构如下:
代码如下:
# -*- coding:utf-8 -*- import uuid import time from celery import Celery from flask import Flask,request,jsonify # 注意这里Flask的实例名称不能叫app,否则会报错! flask_app = Flask(__name__) flask_app.config["CELERY_BROKER_URL"] = "redis://localhost:6379/1" flask_app.config["CELERY_RESULT_BACKEND"] = "redis://localhost:6379/2" # celery实例 celery_ins = Celery(flask_app.name,broker=flask_app.config["CELERY_BROKER_URL"]) celery_ins.conf.update(flask_app.config) # 模拟处理发送邮件的函数 def do_send_email(to,content): start = time.time() time.sleep(3) print(f"测试发邮件的处理过程...耗时 {time.time() - start} s") # 异步任务 @celery_ins.task def send_email(to,content): do_send_email(to,content) return "send email successfully!" # Flask视图函数 —— 在里面调用异步任务 @flask_app.route("/pwd/forgot",methods=["POST"]) def reset_pwd(): args = request.args email = args["email"] token = str(uuid.uuid4()) content = u'请点击链接重置密码:http://example.com/password/reset/?token=%s' % token # 调用异步任务 send_email.delay(email,content) return jsonify(code=0,msg="邮件发送成功!") if __name__ == '__main__': flask_app.run(debug=True,host="127.0.0.1",port=9000)
运行celery与flask项目
运行celery
进入项目的目录:
执行celery命令:
启动flask项目
在postman中模拟