LoginSignup
0
4

More than 5 years have passed since last update.

Azure FunctionsのHTTPトリガーでBlob Storageにある画像をSAS URLからダウンロードして表示する(Azure Functions v1、Python 3.6.1)

Posted at

Azure FunctionsのHTTPトリガーでBlob Storageにある画像を表示する(Azure Functions v1、Python 3.6.1)の続きです。

前の記事では、Blobへのアクセスができる状態でしたので、SASを生成して一時的にアクセス権限を付与し、ダウンロード表示させるようにしましょう。

Blobのアクセスレベルの変更

対象のコンテナにチェックを入れ、アクセスレベルを変更しますをクリックします。
azure27.PNG

前の記事ではBlobへのアクセスを許可していましたが、プライベートに変更します。
azure28.PNG

これで、BlobのURLからアクセスしても表示できません。
azure29.PNG

Function Appの関数を作成

SASを生成(1時間のアクセス許可)し、SASトークンを含むSAS URLをHTMLタグに入れることで、画像を表示します。

import os
import json
from datetime import datetime, timedelta, timezone
from azure.storage.blob import BlockBlobService
from azure.storage.blob import ContainerPermissions
import requests
import base64

account_name = '{your-storage-account}'
account_key = '{your-storage-account-key}'
container_name = 'test'

service = BlockBlobService(account_name=account_name, account_key=account_key)
sas_token = service.generate_container_shared_access_signature(container_name, ContainerPermissions.READ, datetime.utcnow() + timedelta(hours=1))
print (sas_token)

blobs = service.list_blobs(container_name)

files = []
for blob in blobs:
    files.append(blob.name)

# response HTML
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))

sas_url = "https://{your-storage-account}.blob.core.windows.net/" + container_name + "/" + files[0] + "?"+ sas_token
write_http_response(200, "<html><h1>" + files[0] + "</h1><img src=" + "\"" + sas_url + "\"" + ">" + "</html>")

下記でも表示できます。requestsでSAS URLから画像をダウンロードした後、HTMLタグにbase64エンコードした画像データを入れています。

ret = requests.get("https://{your-storage-account}.blob.core.windows.net/" + container_name + "/" + files[0] + "?"+ sas_token)
print(ret)

# response HTML base64 binary
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))

ret = requests.get("https://{your-storage-account}.blob.core.windows.net/" + container_name + "/" + files[0] + "?"+ sas_token)
print(ret)
img = base64.b64encode(ret.content)
write_http_response(200, "<html><h1>" + files[0] + "</h1><img src=" + "\"data:image/jpg;base64," + img.decode() + "\"" + ">" + "</html>")

前の記事同様に、保存して実行、関数のURLからlena.jpgが表示されたらOKです。

まとめ

  • SAS URLを用いて画像をダウンロードして表示しました
  • Function AppのAPI keyをユーザーごとに発行したいですね

参考文献

0
4
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
0
4