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

如何在Python版Google Cloud Functions中调用Cloud Storage中的密钥文件

从Google Cloud Storage读取密钥文件用于Cloud Functions

前提准备

确保Cloud Functions使用的默认服务账号(格式为[项目ID]@appspot.gserviceaccount.com)拥有目标GCS存储桶的Storage Object Viewer权限,否则会无法读取密钥文件。

实现方案

由于service_account.Credentials.from_service_account_file()需要本地文件路径,而GCS中的文件无法直接作为本地路径引用,因此需要先将文件内容读取到内存或临时文件中,再生成凭证。

方案1:读取到内存(推荐,无需写临时文件)

from google.cloud import storage
from google.oauth2 import service_account
from google.cloud import bigquery
import json

def your_function_handler(request):
    # 替换为你的存储桶名称和密钥文件路径
    bucket_name = "your-bucket-name"
    key_blob_path = "path/to/your/service-account-key.json"

    # 初始化GCS客户端(使用默认服务账号权限)
    storage_client = storage.Client()
    bucket = storage_client.bucket(bucket_name)
    key_blob = bucket.blob(key_blob_path)

    # 读取密钥文件内容并转为字典
    key_content = key_blob.download_as_text()
    key_dict = json.loads(key_content)

    # 生成BigQuery客户端凭证
    credentials = service_account.Credentials.from_service_account_info(key_dict)
    bq_client = bigquery.Client(credentials=credentials, project=credentials.project_id)

    # 这里添加你的业务逻辑代码
    # ...

    return "执行完成"

方案2:下载到临时文件

Cloud Functions提供可写的/tmp临时目录,可将GCS文件下载到此处再使用:

from google.cloud import storage
from google.oauth2 import service_account
from google.cloud import bigquery
import os

def your_function_handler(request):
    bucket_name = "your-bucket-name"
    key_blob_path = "path/to/your/service-account-key.json"
    temp_key_path = "/tmp/service-account-key.json"

    # 下载密钥文件到临时路径
    storage_client = storage.Client()
    bucket = storage_client.bucket(bucket_name)
    key_blob = bucket.blob(key_blob_path)
    key_blob.download_to_filename(temp_key_path)

    # 生成凭证并初始化BigQuery客户端
    credentials = service_account.Credentials.from_service_account_file(temp_key_path)
    bq_client = bigquery.Client(credentials=credentials, project=credentials.project_id)

    # 可选:用完临时文件后删除
    os.remove(temp_key_path)

    # 业务逻辑代码
    # ...

    return "执行完成"

优化建议

  • 避免硬编码存储桶和文件路径,可通过Cloud Functions的环境变量配置,比如用os.environ.get("BUCKET_NAME")获取对应值,提升代码灵活性和安全性。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.05 14:10:26