升级Python与google-cloud-storage后,App Engine调用generate_signed_url失败
解决App Engine Python3.9+google-cloud-storage2.10生成签名URL报错问题
问题原因
新版本google-cloud-storage(2.x及以上)不再支持用App Engine默认的Compute Engine Credentials本地生成签名URL(这类凭证没有私钥),转而推荐使用GCP IAM服务进行签名,这是更安全的官方方案。旧版本能正常运行是因为库内部做了兼容处理,新版本则统一了签名逻辑。
解决方法(无需配置服务账号密钥)
方法一:调用时指定默认服务账号邮箱
修改你的签名URL生成代码,添加service_account_email参数,使用App Engine默认服务账号邮箱(格式为[你的项目ID]@appspot.gserviceaccount.com):
from google.cloud import storage import datetime storage_client = storage.Client() bucket = storage_client.bucket(estate.bucket_name) blob = bucket.blob(blob_name) # 替换为你的项目默认服务账号邮箱 service_account_email = "your-project-id@appspot.gserviceaccount.com" url = blob.generate_signed_url( version="v4", expiration=datetime.timedelta(hours=5), method="GET", service_account_email=service_account_email )
权限配置:需要给该默认服务账号添加Service Account Token Creator角色(在GCP控制台IAM页面找到对应账号,添加此角色),确保它拥有调用IAM签名服务的权限。
方法二:通过环境变量自动启用IAM签名
在App Engine的app.yaml中添加环境变量,让库自动使用IAM服务签名:
env_variables: GOOGLE_CLOUD_STORAGE_USE_IAM_SIGNING: "true"
代码可以保持和原版本基本一致,无需额外参数。同样需要确保默认服务账号拥有Service Account Token Creator角色。
这两种方案都完全依赖App Engine的自动认证机制,不需要手动配置服务账号密钥文件,符合你的需求。
内容的提问来源于stack exchange,提问作者Dev93
相关产品推荐
相关产品推荐

