在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會異步執行這個任務。