Azure FunctionsのHTTPトリガーでBlob Storageにある画像を表示してみましょう。
※Chrome上のAzure Portalの表示がなんか調子悪いのでEdgeでやってます。
Function Appの作成
Azure Portalにログインします。
リソースの作成
からFunction Appを作成します。
できたら、リソースに移動します。
Pythonでやりたいので、ランタイムバージョンを~1
に変更します。
Azure FunctionsでPython3を使うを参考にPythonの設定をします。
https://{your-app-name}.scm.azurewebsites.net/DebugConsole
を開きます。{your-app-name}
にはFunction Appの名前を入れてください。(例:gachimoto-blob)
下記コマンドでPython3をインストールします。
> cd D:\home\site\tools
> nuget.exe install -Source https://www.siteextensions.net/api/v2/ -OutputDirectory D:\home\site\tools python361x64
> mv /d/home/site/tools/python361x64.3.6.1.3/content/python361x64/* /d/home/site/tools/
pipでazure-storageライブラリをインストールしましょう。
> D:\home\site\tools\python.exe -m pip install azure-storage

ストレージアカウントの作成
デプロイが完了したら、リソースへ移動します。
ストレージアカウント名とkey1をメモります。
コンテナの作成
コンテナを作成します。testという名前のコンテナを作成しました。Blobはアクセスできるようにしています。


画像のアップロード
testコンテナへ、lena.jpg
をアップロードしてみました。
Blobのアクセスを可能にしているので、URLから見れてしまいます。
例:https://{your-storage-account}.blob.core.windows.net/test/lena.jpg
Function Appの関数作成
画像のアップロードができたら、Function Appに戻ります。
HttpTriggerPython31の内容を次のようにします。
import os
import json
from azure.storage.blob import BlockBlobService
account_name='{your-storage-account}'
account_key='{your-storage-account-key}'
container_name='test'
service = BlockBlobService(account_name=account_name,account_key=account_key)
blobs = service.list_blobs(container_name)
files = []
for blob in blobs:
files.append(blob.name)
def write_http_response(status, body):
return_dict = {
"status": status,
"body": body,
"headers": {
"Content-Type": "text/html"
}
}
output = open(os.environ['res'], 'w')
output.write(json.dumps(return_dict))
write_http_response(200, "<html><h1>" + files[0] + "</h1><img src=" + "\"" + "https://{your-storage-account}.blob.core.windows.net/test/" + files[0] + "\"" + ">" + "</html>")
account_name
とaccount_key
には、メモったストレージアカウント名とkey1を入れます。
testコンテナの中にあるBlobのリストを取得し、リストの一番最初のファイルのURLをHTMLタグに入れて返しています。
保存および実行
をクリックし、出力が進捗状況200 OKになれば成功です。
<html><h1>lena.jpg</h1><img src="https://{your-storage-account}.blob.core.windows.net/test/lena.jpg"></html>
まとめ
- Azure Functionsを用いて、Blob Storageの画像を表示しました
- GETでHTMLを返すやつができました
- 次はクエリ文字列つけたり、見れる人制限したり、SAS使ったりしたいですよね?