Azure Functions (Python) で複数の関数から共通で参照するクラスを作成
Azure Functionsを利用した開発をする際、複数の関数で共通する処理をまとめたいことがあり、複数の関数から利用するクラスを作成しました。
以下のドキュメントを参考にしました。
絶対と相対の各参照の両方を使用して、関数コードにモジュールをインポートすることができます。 次のインポートは、上記のフォルダー構造に基づいて、関数ファイル <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がありました。ファイルを参照する場合は関数アプリのルートを起点としてパスを指定すればよいようです。
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
Author And Source
この問題について(Azure Functions (Python) で複数の関数から共通で参照するクラスを作成), 我々は、より多くの情報をここで見つけました https://zenn.dev/kaorumori/articles/62807987c95748著者帰属:元の著者の情報は、元のURLに含まれています。著作権は原作者に属する。
Collection and Share based on the CC protocol