Durable Functionsは、複数の処理を同調させて1つのワークフローを構成できるコード実行サービスで、関数と呼ばれるプログラムコードを直列や並列につなげることでひとつの大きなタスクを実行できるようになっている。
今回は、Azure Functions上で動作するPythonアプリケーションでDurable Functionsを利用してみたので、その手順を共有する。
なお、Durable Functionsの詳細については、以下のサイトを参照のこと。
https://www.zead.co.jp/column/durable-functions/
前提条件
下記サイトの手順に従って、Azure Functions上で動作するPythonアプリケーションの作成が完了していること。
やってみたこと
ローカル環境でのDurable Functions動作検証
前提条件のPythonによるAzure Functionsアプリを、Durable Functionsを利用する形に修正し、動作検証を行う。その手順は、以下の通り。
2) requirements.txtに「azure-functions-durable」を追加し、以下の状態にする。

3) コマンドプロンプトで「.venv\scripts\activate」を実行し、仮想環境をアクティブ化する。


4) コマンドプロンプトで「pip install -r requirements.txt」コマンドを実行し、Durable Functions用のライブラリをインストールする。

5) 以下のサイトを参考に、function_app.pyを修正する。
https://learn.microsoft.com/ja-jp/azure/azure-functions/durable/quickstart-python-vscode?tabs=windows
修正後のfunction_app.pyは、以下の通り。
import azure.functions as func
import azure.durable_functions as df
import logging
myApp = df.DFApp(http_auth_level=func.AuthLevel.ANONYMOUS)
# An HTTP-triggered function with a Durable Functions client binding
@myApp.route(route="orchestrators/{functionName}")
@myApp.durable_client_input(client_name="client")
async def http_start(req: func.HttpRequest, client):
function_name = req.route_params.get('functionName')
instance_id = await client.start_new(function_name)
response = client.create_check_status_response(req, instance_id)
return response
# Orchestrator
@myApp.orchestration_trigger(context_name="context")
def hello_orchestrator(context):
result1 = yield context.call_activity("hello", "Seattle")
result2 = yield context.call_activity("hello", "Tokyo")
result3 = yield context.call_activity("hello", "London")
logging.info(result1)
logging.info(result2)
logging.info(result3)
return [result1, result2, result3]
# Activity
@myApp.activity_trigger(input_name="city")
def hello(city: str):
return f"Hello {city}"6) 別のコマンドプロンプトでazuriteを実行しつつ、コマンドプロンプトで「func start」コマンドを実行する。


7) ブラウザ上で「http://localhost:7071/api/orchestrators/hello_orchestrator」にアクセスすると、以下のように、ログに赤枠の「Hello (都市名)」が出力されているのが確認できる。


Azure上でのDurable Functions動作検証
Azure上でのDurable Functions動作検証は、以下の記事の「Azure上でのAzure Functions動作検証」と同じ手順で実施する。
デプロイが完了すると、以下のように、Azure Functions 関数で、3種類の関数が表示されていることが確認できる。

また、ブラウザ上で「https://azurefuncpython.azurewebsites.net/api/orchestrators/hello_orchestrator」にアクセスした後でログを確認すると、以下のように、ログに赤枠の「Hello (都市名)」が出力されているのが確認できる。


要点まとめ
- Durable Functionsは、複数の処理を同調させて1つのワークフローを構成できるコード実行サービスで、関数と呼ばれるプログラムコードを直列や並列につなげることでひとつの大きなタスクを実行できるようになっている。






