azure-storage-blob-py について
azure-storage-blob-pyは、Azure Blob Storageを扱うPythonクライアントライブラリで、非構造化オブジェクトデータを扱う開発者向けです。コンテナーやBlobの操作に同期・非同期の手順を提供し、転送、一覧取得、メタデータ、SASトークンに対応します。
主な機能
- 01サービス・コンテナー・Blobクライアントの作成
- 02Blobのアップロードとダウンロード
- 03名前のプレフィックスによるBlob一覧取得
- 04プロパティとメタデータの読み取り・設定
- 05SASトークンの生成
- 06同期・非同期クライアントの利用
活用シーン
- 01コンテナーへのファイルアップロード
- 02保存オブジェクトのダウンロードや一覧取得
- 03Blobメタデータの管理
- 04大容量ファイル転送の設定調整
インストール
コマンドをコピーしてターミナルで実行します。
$
npx skills add https:/ / github.com/ sickn33/ agentic-awesome-skills --skill azure-storage-blob-pyインストール後、Claude Code で/azure-storage-blob-pyを入力して読み込まれたか確認します。
詳細
Azure Blob Storage SDK for Python
Azure Blob Storage 用のクライアントライブラリです。非構造化データ向けのオブジェクトストレージです。
インストール
pip install azure-storage-blob azure-identity
環境変数
AZURE_STORAGE_ACCOUNT_NAME=<your-storage-account>
# Or use full URL
AZURE_STORAGE_ACCOUNT_URL=https://<account>.blob.core.windows.net
認証
from azure.identity import DefaultAzureCredential
from azure.storage.blob import BlobServiceClient
credential = DefaultAzureCredential()
account_url = "https://<account>.blob.core.windows.net"
blob_service_client = BlobServiceClient(account_url, credential=credential)
クライアント階層
| クライアント | 用途 | 取得元 |
|---|---|---|
BlobServiceClient | アカウントレベルの操作 | 直接インスタンス化 |
ContainerClient | コンテナーの操作 | blob_service_client.get_container_client() |
BlobClient | 単一の Blob の操作 | container_client.get_blob_client() |
実行時の境界
書き込みや削除の前に、アカウント、コンテナー、対象の Blob を正確に確認してください。overwrite=True は内容を置き換えます。スナップショットの削除は、独立して検証された復旧ポリシーがない場合、取り消せないことがあります。必要に応じて最小権限の RBAC と短期間有効な読み取り専用 SAS を使用し、SAS URL やアカウントキーをログに記録しないでください。BytesIO バッファーはダウンロード全体をメモリに保持します。大きなデータにはファイルストリームを使用してください。
基本的なワークフロー
コンテナーの作成
container_client = blob_service_client.get_container_client("mycontainer")
container_client.create_container()
Blob のアップロード
# From file path
blob_client = blob_service_client.get_blob_client(
container="mycontainer",
blob="sample.txt"
)
with open("./local-file.txt", "rb") as data:
blob_client.upload_blob(data, overwrite=True)
# From bytes/string
blob_client.upload_blob(b"Hello, World!", overwrite=True)
# From stream
import io
stream = io.BytesIO(b"Stream content")
blob_client.upload_blob(stream, overwrite=True)
Blob のダウンロード
blob_client = blob_service_client.get_blob_client(
container="mycontainer",
blob="sample.txt"
)
# To file
with open("./downloaded.txt", "wb") as file:
download_stream = blob_client.download_blob()
file.write(download_stream.readall())
# To memory
download_stream = blob_client.download_blob()
content = download_stream.readall() # bytes
# Read into existing buffer
stream = io.BytesIO()
num_bytes = blob_client.download_blob().readinto(stream)
Blob の一覧表示
container_client = blob_service_client.get_container_client("mycontainer")
# List all blobs
for blob in container_client.list_blobs():
print(f"{blob.name} - {blob.size} bytes")
# List with prefix (folder-like)
for blob in container_client.list_blobs(name_starts_with="logs/"):
print(blob.name)
# Walk blob hierarchy (virtual directories)
for item in container_client.walk_blobs(delimiter="/"):
if item.get("prefix"):
print(f"Directory: {item['prefix']}")
else:
print(f"Blob: {item.name}")
Blob の削除
blob_client.delete_blob()
# Delete with snapshots
blob_client.delete_blob(delete_snapshots="include")
パフォーマンスの調整
# Configure chunk sizes for large uploads/downloads
blob_client = BlobClient(
account_url=account_url,
container_name="mycontainer",
blob_name="large-file.zip",
credential=credential,
max_block_size=4 * 1024 * 1024, # 4 MiB blocks
max_single_put_size=64 * 1024 * 1024 # 64 MiB single upload limit
)
# Parallel upload
blob_client.upload_blob(data, max_concurrency=4)
# Parallel download
download_stream = blob_client.download_blob(max_concurrency=4)
SAS トークン
from datetime import datetime, timedelta, timezone
from azure.storage.blob import generate_blob_sas, BlobSasPermissions
sas_token = generate_blob_sas(
account_name="<account>",
container_name="mycontainer",
blob_name="sample.txt",
account_key="<account-key>", # Or use user delegation key
permission=BlobSasPermissions(read=True),
expiry=datetime.now(timezone.utc) + timedelta(hours=1)
)
# Use SAS token
blob_url = f"https://<account>.blob.core.windows.net/mycontainer/sample.txt?{sas_token}"
Blob のプロパティとメタデータ
# Get properties
properties = blob_client.get_blob_properties()
print(f"Size: {properties.size}")
print(f"Content-Type: {properties.content_settings.content_type}")
print(f"Last modified: {properties.last_modified}")
# Set metadata
blob_client.set_blob_metadata(metadata={"category": "logs", "year": "2024"})
# Set content type
from azure.storage.blob import ContentSettings
blob_client.set_http_headers(
content_settings=ContentSettings(content_type="application/json")
)
非同期クライアント
from azure.identity.aio import DefaultAzureCredential
from azure.storage.blob.aio import BlobServiceClient
async def upload_async():
async with DefaultAzureCredential() as credential, BlobServiceClient(account_url, credential=credential) as client:
blob_client = client.get_blob_client("mycontainer", "sample.txt")
with open("./file.txt", "rb") as data:
await blob_client.upload_blob(data, overwrite=True)
# Download async
async def download_async():
async with DefaultAzureCredential() as credential, BlobServiceClient(account_url, credential=credential) as client:
blob_client = client.get_blob_client("mycontainer", "sample.txt")
stream = await blob_client.download_blob()
data = await stream.readall()
ベストプラクティス
- 接続文字列の代わりに DefaultAzureCredential を使用する
- 非同期クライアントには コンテキストマネージャーを使用する
- 再アップロード時は
overwrite=Trueを明示的に設定する - 大きなファイルの転送には
max_concurrencyを使用する - メモリ効率を高めるため、
readall()よりreadinto()を優先する - 階層構造の一覧表示には
walk_blobs()を使用する - Web 配信する Blob には 適切なコンテンツタイプを設定する
使用する場面
このスキルは、概要で説明されているワークフローや操作を実行する場合に適用できます。
制限事項
- このスキルは、タスクが上記の説明範囲に明確に該当する場合にのみ使用してください。
- 出力を、環境固有の検証、テスト、または専門家によるレビューの代わりとして扱わないでください。
- 必要な入力、権限、安全上の境界、または成功基準が不足している場合は、作業を中断して確認してください。
コメント
Markdown 対応