Azure Functions (Python) で複数の関数から共通で参照するクラスを作成


Azure Functionsを利用した開発をする際、複数の関数で共通する処理をまとめたいことがあり、複数の関数から利用するクラスを作成しました。

以下のドキュメントを参考にしました。

https://docs.microsoft.com/ja-jp/azure/azure-functions/functions-reference-python

絶対と相対の各参照の両方を使用して、関数コードにモジュールをインポートすることができます。 次のインポートは、上記のフォルダー構造に基づいて、関数ファイル <project_root>\my_first_function_init_.py 内から機能します。

from shared_code import my_first_helper_function #(absolute)
import shared_code.my_second_helper_function #(absolute)
from . import example #(relative)

共通の処理を記述するクラスの作成

sharedフォルダを作成します。sharedフォルダがPythonのモジュールであることを示すために__init__.pyファイルを作成します。

sharedフォルダにclasses.pyというファイルを作成してBaseContentクラスの処理を記述します。

shared/classes.py
class BaseContent:
    pass

JSONをロードするメソッドを追加

私の場合、それぞれの関数の共通の処理としてJSONのロードがありました。Azure FunctionsからJSONを参照することについては以下のQ&Aがありました。ファイルを参照する場合は関数アプリのルートを起点としてパスを指定すればよいようです。

https://docs.microsoft.com/en-us/answers/questions/516509/azure-function-not-able-to-read-my-json-file-from.html

BaseContentクラスにshared/data.jsonをロードするメソッドを追加します。

shared/classes.py
import json

class BaseContent:
    def load_data(self):
        try:
            data = json.load(open(os.path.join('shared', 'data.json')))
            return data
	except Exception:
	    return

関数からクラスを呼び出し

Azure Functionsのそれぞれの関数から以下のようにしてBaseContentクラスを継承したクラスを作成することができました。

httpTrigger1/__init__.py
from shared.classes import BaseContent

class Content(BaseContent):
    pass