Flaskで非同期タスクを作成する


96

私はFlaskでアプリケーションを書いていますが、WSGI同期とブロッキング以外は非常にうまく機能します。特に、サードパーティのAPIを呼び出すタスクが1つあり、そのタスクが完了するまでに数分かかる場合があります。その呼び出しを行って(実際には一連の呼び出しです)、実行させたいと思います。コントロールがFlaskに戻る間。

私の見解は次のようになります:

@app.route('/render/<id>', methods=['POST'])
def render_script(id=None):
    ...
    data = json.loads(request.data)
    text_list = data.get('text_list')
    final_file = audio_class.render_audio(data=text_list)
    # do stuff
    return Response(
        mimetype='application/json',
        status=200
    )

今、私がやりたいことは

final_file = audio_class.render_audio()

実行して、メソッドが戻るときに実行されるコールバックを提供しますが、Flaskはリクエストの処理を続行できます。これは、Flaskを非同期で実行するために必要な唯一のタスクであり、これを実装するための最良の方法についてアドバイスをお願いします。

私はツイステッドとクラインを見てきましたが、おそらくスレッディングで十分であるため、それらが過剰であるかどうかはわかりません。または、セロリがこれに適していますか?


私は通常これにセロリを使用します...やり過ぎかもしれませんが、afaikスレッドはWeb環境ではうまく機能しません(iirc ...)
Beasley

正しい。ええ-私はちょうどセロリを調査していました。それは良いアプローチかもしれません。Flaskで実装するのは簡単ですか?
ダーウィンテック

heh私はソケットサーバー(flask-socketio)も使用する傾向があり、はい、それは非常に簡単だと思いました...最も難しい部分は、すべてをインストールすることでした
Joran Beasley

4
私はチェックをお勧めします。このアウト。この人は、一般的にフラスコの素晴らしいチュートリアルを書いており、これは非同期タスクをフラスコアプリに統合する方法を理解するのに最適です。
atlspin 2015

回答:


100

Celeryを使用して非同期タスクを処理します。タスクキューとして機能するブローカーをインストールする必要があります(RabbitMQおよびRedisをお勧めします)。

app.py

from flask import Flask
from celery import Celery

broker_url = 'amqp://guest@localhost'          # Broker URL for RabbitMQ task queue

app = Flask(__name__)    
celery = Celery(app.name, broker=broker_url)
celery.config_from_object('celeryconfig')      # Your celery configurations in a celeryconfig.py

@celery.task(bind=True)
def some_long_task(self, x, y):
    # Do some long task
    ...

@app.route('/render/<id>', methods=['POST'])
def render_script(id=None):
    ...
    data = json.loads(request.data)
    text_list = data.get('text_list')
    final_file = audio_class.render_audio(data=text_list)
    some_long_task.delay(x, y)                 # Call your async task and pass whatever necessary variables
    return Response(
        mimetype='application/json',
        status=200
    )

Flaskアプリを実行し、セロリワーカーを実行する別のプロセスを開始します。

$ celery worker -A app.celery --loglevel=debug

また、Meluel Gringbergの記事で、Celery をFlaskで使用するための詳細なガイドを参照します。


34

スレッド化は別の可能なソリューションです。Celeryベースのソリューションは、大規模なアプリケーションに適していますが、問題のエンドポイントで大量のトラフィックを期待していない場合は、スレッド化が実行可能な代替手段です。

このソリューションは、Miguel GrinbergのPyCon 2016 Flask at Scaleプレゼンテーション、特にスライドデッキのスライド41に基づいています。彼のコードは、元のソースに興味がある人のためにgithubでも入手できます

ユーザーの観点から見ると、コードは次のように機能します。

  1. 長期実行タスクを実行するエンドポイントを呼び出します。
  2. このエンドポイントは、タスクのステータスを確認するためのリンクとともに202 Acceptedを返します。
  3. ステータスリンクの呼び出しは、タスクの実行中に202を返し、タスクが完了すると200(および結果)を返します。

api呼び出しをバックグラウンドタスクに変換するには、@ async_apiデコレーターを追加するだけです。

以下は完全に含まれた例です:

from flask import Flask, g, abort, current_app, request, url_for
from werkzeug.exceptions import HTTPException, InternalServerError
from flask_restful import Resource, Api
from datetime import datetime
from functools import wraps
import threading
import time
import uuid

tasks = {}

app = Flask(__name__)
api = Api(app)


@app.before_first_request
def before_first_request():
    """Start a background thread that cleans up old tasks."""
    def clean_old_tasks():
        """
        This function cleans up old tasks from our in-memory data structure.
        """
        global tasks
        while True:
            # Only keep tasks that are running or that finished less than 5
            # minutes ago.
            five_min_ago = datetime.timestamp(datetime.utcnow()) - 5 * 60
            tasks = {task_id: task for task_id, task in tasks.items()
                     if 'completion_timestamp' not in task or task['completion_timestamp'] > five_min_ago}
            time.sleep(60)

    if not current_app.config['TESTING']:
        thread = threading.Thread(target=clean_old_tasks)
        thread.start()


def async_api(wrapped_function):
    @wraps(wrapped_function)
    def new_function(*args, **kwargs):
        def task_call(flask_app, environ):
            # Create a request context similar to that of the original request
            # so that the task can have access to flask.g, flask.request, etc.
            with flask_app.request_context(environ):
                try:
                    tasks[task_id]['return_value'] = wrapped_function(*args, **kwargs)
                except HTTPException as e:
                    tasks[task_id]['return_value'] = current_app.handle_http_exception(e)
                except Exception as e:
                    # The function raised an exception, so we set a 500 error
                    tasks[task_id]['return_value'] = InternalServerError()
                    if current_app.debug:
                        # We want to find out if something happened so reraise
                        raise
                finally:
                    # We record the time of the response, to help in garbage
                    # collecting old tasks
                    tasks[task_id]['completion_timestamp'] = datetime.timestamp(datetime.utcnow())

                    # close the database session (if any)

        # Assign an id to the asynchronous task
        task_id = uuid.uuid4().hex

        # Record the task, and then launch it
        tasks[task_id] = {'task_thread': threading.Thread(
            target=task_call, args=(current_app._get_current_object(),
                               request.environ))}
        tasks[task_id]['task_thread'].start()

        # Return a 202 response, with a link that the client can use to
        # obtain task status
        print(url_for('gettaskstatus', task_id=task_id))
        return 'accepted', 202, {'Location': url_for('gettaskstatus', task_id=task_id)}
    return new_function


class GetTaskStatus(Resource):
    def get(self, task_id):
        """
        Return status about an asynchronous task. If this request returns a 202
        status code, it means that task hasn't finished yet. Else, the response
        from the task is returned.
        """
        task = tasks.get(task_id)
        if task is None:
            abort(404)
        if 'return_value' not in task:
            return '', 202, {'Location': url_for('gettaskstatus', task_id=task_id)}
        return task['return_value']


class CatchAll(Resource):
    @async_api
    def get(self, path=''):
        # perform some intensive processing
        print("starting processing task, path: '%s'" % path)
        time.sleep(10)
        print("completed processing task, path: '%s'" % path)
        return f'The answer is: {path}'


api.add_resource(CatchAll, '/<path:path>', '/')
api.add_resource(GetTaskStatus, '/status/<task_id>')


if __name__ == '__main__':
    app.run(debug=True)

このコードを使用すると、エラーwerkzeug.routing.BuildError:エンドポイント 'gettaskstatus'の値['task_id']でURLを作成できませんでした。何か不足していますか?
Nicolas Dufaur

9

を使っmultiprocessing.Processて試すこともできdaemon=Trueます。このprocess.start()メソッドはブロックせず、高価な関数がバックグラウンドで実行されている間、呼び出し元に即座に応答/ステータスを返すことができます。

falconフレームワークを使用しているdaemonときに、同様の問題が発生し、プロセスの使用が役立ちました。

次のことを行う必要があります。

from multiprocessing import Process

@app.route('/render/<id>', methods=['POST'])
def render_script(id=None):
    ...
    heavy_process = Process(  # Create a daemonic process with heavy "my_func"
        target=my_func,
        daemon=True
    )
    heavy_process.start()
    return Response(
        mimetype='application/json',
        status=200
    )

# Define some heavy function
def my_func():
    time.sleep(10)
    print("Process finished")

すぐに応答が得られ、10秒後にコンソールにメッセージが表示されます。

注:daemonicプロセスは子プロセスの生成を許可されていないことに注意してください。


非同期は、スレッドでもマルチプロセッシングでもない特定のタイプの並行性です。ただし、スレッド化は非同期タスクとして目的がはるかに近くなっています
tortal

3
あなたの言い分がわかりません。作者は非同期タスクについて話しています。これは、「バックグラウンドで」実行されるタスクであり、呼び出し元が応答を受け取るまでブロックしません。デーモンプロセスの生成は、このような非同期を実現できる例です。
Tomasz Bartkowiak

/render/<id>エンドポイントが結果として何かを期待する場合はどうなりますmy_func()か?
ウィル区

my_funcたとえば、他のエンドポイントに応答/ハートビートを送信することができます。または、通信できるメッセージキューを確立して共有することもできますmy_func
Tomasz Bartkowiak
弊社のサイトを使用することにより、あなたは弊社のクッキーポリシーおよびプライバシーポリシーを読み、理解したものとみなされます。
Licensed under cc by-sa 3.0 with attribution required.