LoginSignup
1
0

More than 1 year has passed since last update.

Azure Functions(Python+Matplotlib)

Posted at

概要

公式のドキュメント「クイックスタート: コマンド ラインから Azure に Python 関数を作成する 」を整理・補足したものになります。

最後に、matplotlibを使ってグラフを生成してレスポンスするウェブAPIのサンプルコードを付けています。

動作確認環境

  • Windows Windows 10 Pro 20H2

準備

Azure Functions Core Tools のインストール

Azure Functions Core Tools の最新版をインストールする。コマンドラインからバージョンを確認する。3.0.3734(x64)

AzureFunctionsCoreToolsのバージョン確認
func --version

Azure CLI のインストール と Azureログイン

Azure CLI の最新版をインストールする。コマンドラインからバージョンを確認する。2.28.0

AzureCLIのバージョン確認
az --version

Azure CLI で Azure にログインする。コマンドラインから下記を実行すると、ウェブブラウザが立ち上がるので指示に従って Azure アカウントにログインする。

Azurログイン
az login

Pythonのバージョン確認と仮想環境の設定

Pythonのバージョンを確認する。Function App(関数アプリ)で、Python(ランタイムスタック)は 3.6 から 3.9 に対応している。 ここでは、3.8.5 を想定します。

Pythonバージョン確認
python -V

Pythonの仮想環境 azure-func を作成して有効化する(virtualenv + virtualenvwrapper を想定)。pipのバージョンを最新にする。

mkvirtualenv azure-func
workon azure-func
pip install --upgrade pip

プロジェクトの作成

関数アプリのプロジェクトを管理するためのフォルダ AzureFunc02 を作成して移動する。

cd "C:\Users\xxxx\Documents\Projects\AzureFunc02"

プロジェクトの初期化とHTTPトリガの関数 HttpTrigger01(テンプレートとなるものを自動生成)する。

func new --name HttpTrigger01 --template "HTTP trigger" --authlevel "anonymous"

実行すると Use the up/down arrow keys to select a worker runtime: と尋ねられるので上下キーで Python を選択する。

生成された関数フォルダ HttpTrigger01 に移動する。__init__.pyfunction.json の2ファイルがある。

cd HttpTrigger01

__init__.py を確認して、必要なモジュールをインストールする。また、編集を行なう。

pip install azure.functions 

ローカルでの動作確認

プロジェクト AzureFunc02 のトップフォルダに戻って、ローカルで動作テストをする。

ローカルで動作テスト
func start --python --port 8000

クラウドに発行して動作確認

Azure に xxxx-p-func2 という名前の Function App(関数アプリ)を新規作成する。既にAzureに、XXXX-JapanEast-RG というリソースグループ、storage01xxxx というストレージアカウントが作成済みであることを前提にしています。

Azureにリソース追加
az functionapp create --consumption-plan-location japaneast ^
--runtime python ^
--runtime-version 3.8 ^
--functions-version 3 ^
--name xxxx-p-func2 ^
--os-type linux ^
--resource-group XXXX-JapanEast-RG ^
--storage-account storage01xxxx ^
--disable-app-insights true

ローカルで開発してものを Azure に発行する。

発行する
func azure functionapp publish xxxx-p-func2

補足

  • requirements.txtmatplotlib を追加する。
__init__.py(Matplotlibで画像を生成してレスポンス)
import logging
import io
import numpy as np
import azure.functions as func
import matplotlib
import matplotlib.pyplot as plt

matplotlib.use('Agg')

def main(req: func.HttpRequest) -> func.HttpResponse:
  logging.info('Python HTTP trigger function processed a request.')

  image = io.BytesIO()
  x = np.linspace(0, 10)
  y = np.sin(x)
  plt.plot(x, y)
  plt.savefig(image, format='png')
  image.seek(0)
  return func.HttpResponse(image.read(),mimetype='image/png')

参考資料

  • VS Code の拡張機能で同様のことを行なう。

1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0