在Flask中实现消息队列通常使用Celery这样的异步任务队列库。以下是一个基本的示例:
- 首先,安装Celery库:
pip install celery
- 创建一个Flask应用并配置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任务:
@celery.task def send_email(to, subject, body): # 发送邮件的逻辑 pass
- 在Flask应用中调用Celery任务:
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:
celery worker -A app.celery --loglevel=info
这样就可以在Flask应用中使用Celery实现消息队列功能了。当调用send_email.delay
时,任务会被添加到Celery队列中,Celery worker会异步执行这个任务。