之前在项目中我们发送邮件和 短信都是阻塞的,现在我们来利用Celery来优化它们
官方使用文档: http://flask.pocoo.org/docs/1.0/patterns/celery/
redis服务器及插件,还有cerely在上节我们已经安装好,这里就不重复过程了。
首先,来完成邮件
在项目下新建tasks.py
from flask import Flask import config from celery import Celery from flask_mail import Message from exts import mail ##这里没有直接使用from bbs import app,是因为会出现循环引用的问题 app = Flask(__name__) app.config.from_object(config) mail.init_app(app) #在配置文件需要配置CELERY_RESULT_BACKEND、CELERY_BROKER_UR 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.Task class ContextTask(TaskBase): abstract = True def __call__(self, *args, **kwargs): with app.app_context(): return TaskBase.__call__(self, *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)
编辑config.py
# Celery相关配置 CELERY_RESULT_BACKEND = "redis://10.2.2.120:6379/0" CELERY_BROKER_URL = "redis://10.2.2.120:6379/0"
编辑cms.views.py发送邮件的部分
原文地址:https://www.cnblogs.com/sellsa/p/9757905.html
时间: 2024-11-05 21:43:43