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

如何通过Google Cloud Function将GCS Bucket更新文件上传至Google Drive

实现GCS文件更新自动同步到Google Drive的Cloud Function方案

前置准备

  • 启用Google Cloud控制台中的以下API:Cloud Functions API、Cloud Storage API、Google Drive API
  • 创建一个服务账号,为其添加Storage Object Viewer权限(用于读取GCS存储桶文件),并将目标Google Drive文件夹分享给该服务账号的邮箱(权限设为“编辑”)
  • 下载该服务账号的JSON密钥文件,后续代码中会用到

创建Cloud Function

  1. 进入Google Cloud Functions控制台,点击「创建函数」
  2. 基础配置:填写函数名称,选择运行区域(建议和GCS存储桶同区域)
  3. 触发器配置:
    • 触发器类型选择「Cloud Storage」
    • 事件类型选择「最终创建/更新文件」
    • 指定需要监听的GCS存储桶
  4. 运行环境:选择Python 3.10(或其他稳定版本)

代码实现

1. 配置依赖(requirements.txt)

在函数的「requirements.txt」标签页中添加以下内容:

google-cloud-storage==2.13.0
google-api-python-client==2.108.0
oauth2client==4.1.3

2. 主函数代码(main.py)

将以下代码粘贴到「main.py」标签页,注意替换DRIVE_FOLDER_ID和SERVICE_ACCOUNT_KEY_PATH为你的实际值:

import os
from google.cloud import storage
from googleapiclient.discovery import build
from oauth2client.service_account import ServiceAccountCredentials

# 替换为你的Drive目标文件夹ID
DRIVE_FOLDER_ID = "your-drive-folder-id"
# 替换为服务账号密钥文件的路径(若在Cloud Function中,建议将密钥内容设为环境变量,此处为简化处理)
SERVICE_ACCOUNT_KEY_PATH = "your-service-account-key.json"

def gcs_to_drive(event, context):
    # 获取GCS事件中的文件信息
    bucket_name = event['bucket']
    file_name = event['name']
    
    # 初始化GCS客户端,下载文件到临时目录
    storage_client = storage.Client()
    bucket = storage_client.bucket(bucket_name)
    blob = bucket.blob(file_name)
    temp_file_path = f"/tmp/{file_name}"
    blob.download_to_filename(temp_file_path)
    
    # 初始化Drive客户端
    credentials = ServiceAccountCredentials.from_json_keyfile_name(
        SERVICE_ACCOUNT_KEY_PATH,
        scopes=['https://www.googleapis.com/auth/drive']
    )
    drive_service = build('drive', 'v3', credentials=credentials)
    
    # 上传文件到Drive目标文件夹
    file_metadata = {
        'name': file_name,
        'parents': [DRIVE_FOLDER_ID]
    }
    media_body = temp_file_path
    
    # 上传操作,若Drive中已有同名文件,会自动添加后缀(如"filename (1)")
    drive_service.files().create(
        body=file_metadata,
        media_body=media_body,
        fields='id'
    ).execute()
    
    # 清理临时文件
    os.remove(temp_file_path)

提示:Drive文件夹ID可以从文件夹的URL中获取,格式为https://drive.google.com/drive/folders/[文件夹ID]

部署与测试

  1. 点击「部署」按钮,等待函数部署完成
  2. 手动更新GCS存储桶中的目标文件,触发函数执行
  3. 进入目标Drive文件夹,检查文件是否同步成功;若失败,可在Cloud Functions控制台的「日志」标签页查看错误信息

注意事项

  • Cloud Function的临时目录/tmp最大支持512MB,若同步的文件超过此大小,需要调整方案
  • 确保服务账号的权限配置正确,否则会出现访问被拒绝的错误
  • 若需要覆盖Drive中的同名文件,可在代码中先查询Drive中是否存在该文件,再执行更新操作

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.28 22:07:28