Python从GCP Secret Manager取回Zip文件格式错误排查
问题解决:从GCP Secret Manager取回Zip文件格式错误
你的代码核心问题是多执行了一次base64解码,这直接导致了Zip文件数据损坏。
原因分析
GCP Secret Manager的Python客户端与gcloud命令的返回逻辑不同:
gcloud命令输出的JSON结果中,payload.data是base64编码的字符串,所以需要解码才能得到原始二进制数据;- 而Python SDK的
response.payload.data已经是解码后的原始字节数据,不需要再手动调用base64.b64decode。
修正后的代码
from google.cloud import secretmanager client = secretmanager.SecretManagerServiceClient() PROJECT_ID = "project" secret_id = "secret" version_id = 1 name = f"projects/{PROJECT_ID}/secrets/{secret_id}/versions/{version_id}" response = client.access_secret_version(name=name) # 直接使用SDK返回的原始字节数据,无需额外解码 bytes_returned = response.payload.data with open("my_zip.zip", "wb") as binary_file: binary_file.write(bytes_returned)
关于本地测试的补充
你提到读取本地有效Zip文件写入新文件也出错,大概率是测试代码中错误地对原始字节做了base64解码操作。正常的本地二进制文件读写应该是这样的:
# 正确的本地Zip文件复制示例 with open("original_valid.zip", "rb") as source_file: raw_data = source_file.read() with open("copied_valid.zip", "wb") as target_file: target_file.write(raw_data)
这样复制出的文件不会出现格式错误。
内容的提问来源于stack exchange,提问作者Cmac199
相关产品推荐
相关产品推荐

