简介
微软官方 Azure Blob Storage Python SDK 开发指南,提供完整代码示例与最佳实践,助力高效构建企业级云存储应用。
原始描述
Azure Blob Storage SDK for Python. Use for uploading, downloading, listing blobs, managing containers, and blob lifecycle. Triggers: "blob storage", "BlobServiceClient", "ContainerClient", "BlobClient", "upload blob", "download blob".
中文使用说明 来自收录源
核心用法
本 Skill 是 Azure Blob Storage SDK for Python 的官方文档型引用指南,涵盖从基础配置到高级优化的完整工作流:
- 客户端层级:
BlobServiceClient(账户级)→ContainerClient(容器级)→BlobClient(单 Blob 级),支持分层管理 - 核心操作:容器创建、Blob 上传(文件/字节/流)、下载(到文件/内存)、列表查询(支持前缀过滤与层级遍历)、删除(含快照选项)
- 性能调优:分块大小配置(4 MiB/64 MiB)、并行传输(
max_concurrency)、内存优化读取(readinto()) - 安全特性:SAS Token 生成、Blob 元数据与属性管理、异步客户端支持(
aio模块) - 认证方式:推荐
DefaultAzureCredential实现无密钥认证,避免硬编码账户密钥
显著优点
- 权威来源:Microsoft 官方 Azure SDK 文档,API 签名与最新版本同步
- 完整性高:覆盖同步/异步双模式、生产级性能优化、安全最佳实践
- 零代码风险:纯文档型 Skill,无实际执行代码,无供应链攻击面
- 即插即用:提供可直接运行的代码片段,支持多种数据源(文件、内存流、字节)
潜在局限
- 环境依赖:需预先配置 Azure 订阅与存储账户,本地开发需模拟器(Azurite)或真实账户
- SDK 版本敏感:部分 API 参数随
azure-storage-blob版本迭代变化,需锁定版本号 - 权限复杂度:RBAC 与 SAS 权限模型较复杂,新手易配置过度宽松权限
- 网络延迟敏感:大文件传输性能受地域与网络质量影响,需配合 CDN 或就近区域部署
适合人群
- 云原生开发者:构建基于 Azure 的数据管道、备份系统、静态网站托管
- DevOps/数据工程师:自动化存储账户管理、生命周期策略实施
- Python 后端开发:需要对象存储替代本地文件系统的微服务场景
- 企业迁移团队:从 AWS S3/GCS 迁移至 Azure Blob 的技术适配
常规风险
| 风险类型 | 说明 | 缓解建议 |
|---|---|---|
| 凭证泄露 | 误将账户密钥提交至代码仓库 | 强制使用 DefaultAzureCredential + Azure AD |
| SAS Token 过期配置不当 | 长期有效 Token 泄露后难以撤销 | 设置最短必要有效期,配合 IP 白名单 |
| 数据误删 | overwrite=True + 错误容器名导致覆盖 |
启用软删除、版本控制,生产环境禁用 overwrite 或加确认逻辑 |
| 成本失控 | 频繁 List 操作或大文件高频传输 | 使用前缀过滤减少 List 开销,配置生命周期策略归档冷数据 |
技能正文
name: azure-storage-blob-py description: | Azure Blob Storage SDK for Python. Use for uploading, downloading, listing blobs, managing containers, and blob lifecycle. Triggers: "blob storage", "BlobServiceClient", "ContainerClient", "BlobClient", "upload blob", "download blob". license: MIT metadata: author: Microsoft version: "1.0.0" package: azure-storage-blob
Azure Blob Storage SDK for Python
Client library for Azure Blob Storage — object storage for unstructured data.
Installation
pip install azure-storage-blob azure-identity
Environment Variables
AZURE_STORAGE_ACCOUNT_NAME=<your-storage-account> # Required for all auth methods
# Or use full URL
AZURE_STORAGE_ACCOUNT_URL=https://<account>.blob.core.windows.net # Alternative to account name
AZURE_TOKEN_CREDENTIALS=prod # Required only if DefaultAzureCredential is used in production
Authentication & Lifecycle
🔑 Two rules apply to every code sample below:
- Prefer
DefaultAzureCredential. It works locally (Azure CLI / VS Code / Developer CLI) and in Azure (managed identity, workload identity) with no code change. Avoid connection strings, account/API keys — they bypass Entra audit and rotation.
- Local dev:
DefaultAzureCredentialworks as-is.- Production: set
AZURE_TOKEN_CREDENTIALS=prod(orAZURE_TOKEN_CREDENTIALS=<specific_credential>) to constrain the credential chain to production-safe credentials.- Wrap every client in a context manager so HTTP transports, sockets, and token caches are released deterministically:
- Sync:
with <Client>(...) as client:- Async:
async with <Client>(...) as client:andasync with DefaultAzureCredential() as credential:(fromazure.identity.aio)Snippets may abbreviate this setup, but production code should always follow both rules.
from azure.identity import DefaultAzureCredential, ManagedIdentityCredential
from azure.storage.blob import BlobServiceClient
# Local dev: DefaultAzureCredential. Production: set AZURE_TOKEN_CREDENTIALS=prod or AZURE_TOKEN_CREDENTIALS=<specific_credential>
credential = DefaultAzureCredential(require_envvar=True)
# Or use a specific credential directly in production:
# See https://learn.microsoft.com/python/api/overview/azure/identity-readme?view=azure-python#credential-classes
# credential = ManagedIdentityCredential()
account_url = "https://<account>.blob.core.windows.net"
with BlobServiceClient(account_url, credential=credential) as blob_service_client:
# Use blob_service_client here (see following sections for operations)
...
Client Hierarchy
| Client | Purpose | Get From |
|---|---|---|
BlobServiceClient |
Account-level operations | Direct instantiation |
ContainerClient |
Container operations | blob_service_client.get_container_client() |
BlobClient |
Single blob operations | container_client.get_blob_client() |
Core Workflow
Create Container
container_client = blob_service_client.get_container_client("mycontainer")
container_client.create_container()
Upload 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)
Download 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)
List Blobs
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}")
Delete Blob
blob_client.delete_blob()
# Delete with snapshots
blob_client.delete_blob(delete_snapshots="include")
Performance Tuning
# Configure chunk sizes for large uploads/downloads
with 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
) as blob_client:
# Parallel upload
blob_client.upload_blob(data, max_concurrency=4)
# Parallel download
download_stream = blob_client.download_blob(max_concurrency=4)
SAS Tokens (User Delegation)
Generate SAS tokens with a user delegation key signed by Microsoft Entra ID — never with an account key. This keeps SAS issuance tied to Entra audit/rotation.
from datetime import datetime, timedelta, timezone
from azure.identity import DefaultAzureCredential
from azure.storage.blob import (
BlobServiceClient,
BlobSasPermissions,
generate_blob_sas,
)
now = datetime.now(timezone.utc)
account_url = "https://<account>.blob.core.windows.net"
with BlobServiceClient(account_url, credential=DefaultAzureCredential()) as service:
# Get a user delegation key (valid up to 7 days). Caller needs the
# "Storage Blob Delegator" role on the storage account.
udk = service.get_user_delegation_key(
key_start_time=now,
key_expiry_time=now + timedelta(hours=1),
)
sas_token = generate_blob_sas(
account_name="<account>",
container_name="mycontainer",
blob_name="sample.txt",
user_delegation_key=udk,
permission=BlobSasPermissions(read=True),
expiry=now + timedelta(hours=1),
)
blob_url = f"{account_url}/mycontainer/sample.txt?{sas_token}"
Blob Properties and Metadata
# 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")
)
Async Client
from azure.identity.aio import DefaultAzureCredential
from azure.storage.blob.aio import BlobServiceClient
async def upload_async():
async with DefaultAzureCredential() as credential:
async with 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 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()
Best Practices
- Pick sync OR async and stay consistent. Do not mix
azure.storage.blobsync clients withazure.storage.blob.aioasync clients in the same call path. Choose one mode per module. - Always use context managers for clients and async credentials. Wrap every client in
with BlobServiceClient(...) as client:(sync) orasync with BlobServiceClient(...) as client:(async). For asyncDefaultAzureCredentialfromazure.identity.aio, also useasync with credential:so tokens and transports are cleaned up. - Use
DefaultAzureCredentialfor code that runs locally (instead of connection strings). Use a specific token credential for code that runs in Azure. - Set
overwrite=Trueexplicitly when re-uploading - Use
max_concurrencyfor large file transfers - Prefer
readinto()overreadall()for memory efficiency - Use
walk_blobs()for hierarchical listing - Set appropriate content types for web-served blobs
Reference Files
| File | Contents |
|---|---|
| references/capabilities.md | Capability index mapping hero flows and non-hero references. |
| references/non-hero-scenarios.md | Dedicated non-hero examples (metadata/properties and async patterns). |
其他来源收录
同一技能在不同目录的原始页面: