Flask+celeryベース

1712 ワード

Celeryはキューベースのタスク処理システムであり、1つのジョブがある場合にメッセージキューにジョブを置くことができ(redisを用いることができる)、その後労働者はタスクをキューから取り出し、処理が完了した後、タスク結果を結果格納容器に置く(mongoであってもよい).
サンプルコード(test.py):
from flask import Flask
from celery import Celery
from celery.result import AsyncResult
import time

app = Flask(__name__)
#         
app.config['CELERY_BROKER_URL'] = 'redis://127.0.0.1:6379/0'
#         
app.config['CELERY_RESULT_BACKEND'] = 'redis://127.0.0.1:6379/0'

celery_ = Celery(app.name, broker=app.config['CELERY_BROKER_URL'])
celery_.conf.update(app.config)

@celery_.task
def my_background_task(arg1, arg2):
     #     
     time.sleep(10)
     return arg1+arg2

@app.route("/sum//")
def sum_(arg1,arg2):
    #      celery,     ID,         ID      
    result = my_background_task.delay(int(arg1),int(arg2))
    return result.id

@app.route("/get_result/")
def get_result(result_id):
    #     ID      
    result = AsyncResult(id=result_id)
    return str(result.get())

起動時にflaskアプリケーションとceleryアプリケーションをそれぞれ起動する必要があります.
gunicorn test:app -b 0.0.0.0:7656
celery -A test.celery_ worker

その後、リンクを使用してタスクを送信し、タスクIDを取得できます.
http://127.0.0.1:7656/sum/1/2

次に、10 s待ってから、次のリンクを使用してタスクの結果を取得します.
http://127.0.0.1:7656/get_result/XXXX(  ID)

また、flowerモジュールでceleryのタスクをモニタし、pipを使用してインストールした後、次のコマンドで起動できます.
flower --basic_auth=admin:admin --broker=redis://127.0.0.1:6379/0 --address=0.0.0.0 --port=5556

次のurlでceleryタスク処理状態(アカウントパスワードはadmin)を監視できます.
http://127.0.0.1:5556