如何本地测试调用Google Cloud Storage的Google Cloud Function
本地使用Functions Framework测试Cloud Function时读取Google Cloud Storage文件的认证问题
问题场景
本地通过functions_framework --target=file_trigger测试Cloud Function,无关联服务依赖时运行正常,但读取Google Cloud Storage(GCS)文件时抛出以下认证错误:
google.auth.exceptions.RefreshError: ('invalid_grant: Token has been expired or revoked.', {'error': 'invalid_grant', 'error_description': 'Token has been expired or revoked.'})
用户提供的测试代码:
from google.cloud import storage # Main entry point for the cloud function def file_trigger(request): event = { 'bucket': 'my-cloud-bucket', 'name': 'my-bucket-file.csv' } bucketName = event['bucket'] blobName = event['name'] storage_client = storage.Client() bucket = storage_client.bucket(bucket_name) blob = bucket.blob(blob_name) with blob.open("r") as f: return f.read()
解决方案
1. 修复代码变量名错误
首先修正代码中的变量名不一致问题:将bucket_name改为bucketName,blob_name改为blobName,否则即使认证正常也会抛出变量未定义错误:
from google.cloud import storage # Main entry point for the cloud function def file_trigger(request): event = { 'bucket': 'my-cloud-bucket', 'name': 'my-bucket-file.csv' } bucketName = event['bucket'] blobName = event['name'] storage_client = storage.Client() bucket = storage_client.bucket(bucketName) # 修正变量名 blob = bucket.blob(blobName) # 修正变量名 with blob.open("r") as f: return f.read()
2. 配置本地认证凭据
本地运行时,Cloud Storage SDK需要有效的Google Cloud认证凭据才能访问资源,以下两种方式任选其一:
方式一:使用应用默认凭据(交互式场景推荐)
- 确保已安装Google Cloud CLI(gcloud)
- 执行命令登录并获取本地应用默认凭据:
gcloud auth application-default login - 按照提示在浏览器中登录你的Google Cloud账号,完成授权后,SDK会自动加载该凭据,无需修改代码,直接运行
functions_framework --target=file_trigger即可。
方式二:使用服务账号密钥文件(自动化/无交互场景推荐)
- 从Google Cloud控制台下载服务账号JSON密钥:进入IAM与Admin > 服务账号,选择拥有GCS读写权限的服务账号,点击密钥 > 添加密钥 > 创建新密钥,选择JSON格式下载。
- 设置环境变量指向密钥文件路径:
- Windows(命令提示符):
set GOOGLE_APPLICATION_CREDENTIALS=C:\路径\到\你的\密钥文件.json - Windows(PowerShell):
$env:GOOGLE_APPLICATION_CREDENTIALS="C:\路径\到\你的\密钥文件.json" - Linux/macOS:
export GOOGLE_APPLICATION_CREDENTIALS=/路径/到/你的/密钥文件.json
- Windows(命令提示符):
- 运行Functions Framework命令:
functions_framework --target=file_trigger
内容的提问来源于stack exchange,提问作者Finglish
相关产品推荐
相关产品推荐

