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

Pydrive访问共享Google Drive:可读无法写入,报404/403错误求助

Google Drive TeamDrive 文件创建报错(404/403)修复方案

错误原因分析

  • 404错误:创建文件的metadata中错误添加了'id': folder_id字段,该字段用于指定需修改的已有文件ID,填入文件夹ID后,API会尝试查找对应ID的文件,最终因找不到返回"File not found"。
  • 403错误:
    1. parents字段格式错误:TeamDrive下指定父文件夹需同时包含文件夹ID和TeamDrive ID,而非仅填写teamDriveId。
    2. supportsTeamDrives、includeTeamDriveItems属于API请求参数,不应放在文件metadata中,需在上传时传递。

修复后的创建文件代码

def authenticate_drive(drive_json_path: str):
    """Authenticate and return the GoogleDrive object.
    
    Args:
    drive_json_path (str): Contains the path to the Google Drive .json credentials file
    
    Returns:
    drive (GoogleAuth): Returns a GoogleAuth session that allows making API calls
    """
    gauth = GoogleAuth()
    gauth.credentials = sca.from_json_keyfile_name(drive_json_path, ['https://www.googleapis.com/auth/drive'])
    drive = GoogleDrive(gauth)
    return drive

def create_text_file(drive, folder_id, content):
    # Create a text file with the specified content
    file_metadata = {
        'title': 'hello.txt',
        'parents': [{
            'id': folder_id,
            'teamDriveId': team_drive_id
        }]
    }
            
    file_content = drive.CreateFile(file_metadata)
    file_content.SetContentString(content)
    # 传递TeamDrive支持参数到Upload方法
    file_content.Upload({
        'supportsTeamDrives': True,
        'includeTeamDriveItems': True
    })

    print(f'Text file created with ID: {file_content.get("id")}')

drive = authenticate_drive(credentials_path)
create_text_file(drive, folder_id, content)

关键修改点说明

  • 移除metadata中的'id': folder_id,避免API错误触发文件查找逻辑
  • 修正parents字段结构,同时传入目标文件夹ID和TeamDrive ID
  • 将supportsTeamDrives、includeTeamDriveItems移至Upload()方法的参数中,符合PyDrive的API调用规范

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.05 00:27:10