运行本文件
linux上 # celery -A tasks.celery worker -l info
window上 # celery -A tasks.celery worker --pool=solo -l info
在项目文件夹下建立tasks.py文件
from flask import Flask
from config import Config
from celery import Celery
from flask_mail import Message
from flask_mail import Mail
##这里没有直接使用from bbs import app,是因为会出现循环引用的问题
mail = Mail()
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['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,sender,recipients,body):
message = Message(subject=subject,sender=sender,recipients=recipients,body=body)
mail.send(message)
config.py中配置:
SQLALCHEMY_TRACK_MODIFICATIONS = False
MAIL_SERVER = os.environ.get('MAIL_SERVER')
MAIL_PORT = int(os.environ.get('MAIL_PORT') or 25)
MAIL_USE_TLS = os.environ.get('MAIL_USE_TLS') is not None
MAIL_USERNAME = os.environ.get('MAIL_USERNAME')
MAIL_PASSWORD = os.environ.get('MAIL_PASSWORD')
# ADMINS = ['your-email@example.com']
RESULT_BACKEND = "redis://127.0.0.1:6379/0"
CELERY_BROKER_URL = "redis://127.0.0.1:6379/0"
然后在程序中调用该函数
def send_password_reset_email(user):
tasks.send_mail.delay('sad',current_app.config['MAIL_USERNAME'],['123@qq.com'],'sdasd')
在windows下运行脚本
celery -A tasks.celery worker --pool=solo -l info
然后启动项目即可 可以试试