You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用Python SDK从Azure存储账户创建静态网站托管

使用Azure Python SDK配置存储账户静态网站托管

以下是通过BlobServiceClient配置Azure存储账户静态网站托管的完整代码实现,包含初始化客户端、配置静态网站属性以及上传必要页面的步骤:

1. 安装依赖

确保已安装所需的Python包:

pip install azure-storage-blob azure-identity

2. 配置静态网站的核心代码

from azure.storage.blob import BlobServiceClient
from azure.identity import DefaultAzureCredential

# 替换为你的存储账户名称
STORAGE_ACCOUNT_NAME = "your-storage-account-name"
account_url = f"https://{STORAGE_ACCOUNT_NAME}.blob.core.windows.net"

# 初始化BlobServiceClient(推荐使用Azure AD身份验证,生产环境更安全)
credential = DefaultAzureCredential()
blob_service_client = BlobServiceClient(account_url, credential=credential)

# 或者使用存储账户连接字符串(快速测试场景)
# connection_string = "your-storage-account-connection-string"
# blob_service_client = BlobServiceClient.from_connection_string(connection_string)

# 配置静态网站参数:启用托管,设置索引页和错误页
static_site_settings = {
    "enabled": True,
    "index_document": {"name": "index.html"},
    "error_document": {"name": "404.html"}
}

# 应用配置到存储账户
blob_service_client.set_service_properties(static_website=static_site_settings)
print("静态网站托管已成功启用并配置")

3. 上传静态页面到$web容器

静态网站的文件需要存储在自动创建的$web容器中,以下是上传索引页和错误页的示例:

# 获取$web容器客户端
web_container_client = blob_service_client.get_container_client("$web")

# 上传index.html
with open("path/to/your/index.html", "rb") as index_file:
    web_container_client.upload_blob(
        name="index.html",
        data=index_file,
        overwrite=True
    )

# 上传404.html
with open("path/to/your/404.html", "rb") as error_file:
    web_container_client.upload_blob(
        name="404.html",
        data=error_file,
        overwrite=True
    )

print("静态页面上传完成")

关键说明

  • set_service_properties是配置静态网站的核心方法,通过static_website参数传入配置即可启用托管。
  • 若$web容器不存在,SDK会自动创建。
  • 访问静态网站的URL格式为:https://<your-storage-account-name>.z6.web.core.windows.net(区域不同可能略有差异,可在Azure门户确认)。
  • 确保使用的身份验证主体拥有存储账户的Storage Account Contributor或Storage Blob Data Owner权限,否则会出现权限不足的错误。

内容的提问来源于stack exchange,提问作者Sandhu

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.02 05:42:12