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

使用Python生成容器SAS时遇Base64编码无效错误求助

解决Azure容器SAS生成时的Base64编码错误

问题重现

使用Python生成Azure容器共享访问签名(SAS)时触发以下错误:

Exception: Invalid base64-encoded string: number of data characters (85) cannot be 1 more than a multiple of 4

使用的代码:

sas_token = generate_container_sas(
            account_name=account_name,
            container_name=settings.AZURE_CONTAINER_NAME,
            account_key=account_key,
            permission=BlobSasPermissions(read=True),
            expiry=expiry_time,
            start=start_time
        )

问题原因

这个错误几乎都是由存储账户密钥(account_key)格式无效导致的:

  • Azure存储账户密钥是标准Base64编码字符串,正常长度为88字符(含末尾等号),你的密钥只有85个有效字符,说明被截断、修改或包含无效内容。
  • 常见场景:复制密钥时遗漏部分字符,或者密钥字符串中混入了换行、空格等额外字符。

解决方法

  • 重新获取并校验账户密钥:
    登录Azure门户,进入目标存储账户的「访问密钥」页面,复制主密钥或副密钥的完整字符串,确保没有遗漏或多余字符。
  • 清理密钥中的无效字符:
    对传入的account_key做预处理,去除首尾空白和换行符:
    account_key = account_key.strip().replace('\n', '').replace('\r', '')
    
  • 验证密钥的Base64有效性:
    用以下代码快速测试密钥是否合法:
    import base64
    try:
        base64.b64decode(account_key)
        print("密钥Base64格式有效")
    except Exception as e:
        print(f"密钥无效:{e}")
    
  • 确认时间参数类型:
    确保expiry_time和start_time是UTC时间的datetime对象,而非字符串,例如:
    from datetime import datetime, timedelta
    start_time = datetime.utcnow()
    expiry_time = start_time + timedelta(hours=1)
    

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.10 23:32:49