在Flask中实现消息队列通常使用Celery这样的异步任务队列库。以下是一个基本的示例:
pip install celery
from flask import Flask
from celery import Celery
app = Flask(__name__)
# 配置Celery
app.config['CELERY_BROKER_URL'] = 'redis://localhost:6379/0'
app.config['CELERY_RESULT_BACKEND'] = 'redis://localhost:6379/0'
celery = Celery(app.name, broker=app.config['CELERY_BROKER_URL'])
celery.conf.update(app.config)
@celery.task
def send_email(to, subject, body):
# 发送邮件的逻辑
pass
from tasks import send_email
@app.route('/send_email')
def send_email_view():
send_email.delay('example@example.com', 'Subject', 'Body')
return 'Email sent!'
celery worker -A app.celery --loglevel=info
这样就可以在Flask应用中使用Celery实现消息队列功能了。当调用send_email.delay
时,任务会被添加到Celery队列中,Celery worker会异步执行这个任务。