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

使用Python API无人值守上传Google Drive遇权限错误求助

解决Google Drive API无人值守上传的授权问题

问题背景

我需要实现无人值守将视频文件上传至Google Drive,计划使用Google Drive API,但遇到两个核心问题:

  • 使用服务账号时,文件所有者是服务账号邮箱,而非我自己的Google Drive账号,且文件存储位置管理不便;
  • 使用OAuth方式会弹出登录网页,令牌过期快,无法满足无人值守需求。

我尝试用服务账号模拟用户身份上传,代码如下:

import googleapiclient.discovery
from google.oauth2.service_account import Credentials

# Load service account credentials from JSON key file
SERVICE_ACCOUNT_KEY_FILE = 'apikeys.json'
SCOPES = ['https://www.googleapis.com/auth/drive']

def impersonate_user(user_email):
    credentials = Credentials.from_service_account_file(SERVICE_ACCOUNT_KEY_FILE, scopes=SCOPES)
    credentials = credentials.with_subject(user_email)
    return credentials

def upload_file_to_drive(credentials, file_path, folder_id):
    drive_service = googleapiclient.discovery.build('drive', 'v3', credentials=credentials)

    file_metadata = {'name': 'my_video.mp4', 'parents': [folder_id]}
    media = googleapiclient.http.MediaFileUpload(file_path, mimetype='video/mp4')
    uploaded_file = drive_service.files().create(
        body=file_metadata, media_body=media, fields='id').execute()

    print(f'File uploaded with ID: {uploaded_file["id"]}')

if __name__ == '__main__':
    # Replace with the user's email and target folder ID
    user_email = 'osara.jenkins.rt@gmail.com'
    target_folder_id = '1unzEKIYnXnBlYEaJxIEiWpHM2MA-Du6D'
    video_file_path = r'C:\Users\M000747\OneDrive - Osara Technologies Limited\Desktop\coding\zoom_download\2024-02-27_17-44-15\CSEC Integrated Science\CSEC Integrated Science_shared_screen_with_speaker_view_2024-02-24T22_35_06Z.mp4'

    user_credentials = impersonate_user(user_email)
    upload_file_to_drive(user_credentials, video_file_path, target_folder_id)

运行后出现错误:

raise exceptions.RefreshError(
google.auth.exceptions.RefreshError: ('unauthorized_client: Client is unauthorized to retrieve access tokens using this method, or client not authorized for any of the scopes requested.', {'error': 'unauthorized_client', 'error_description': 'Client is unauthorized to retrieve access tokens using this method, or client not authorized for any of the scopes requested.'})

错误原因

这个错误的核心是服务账号未被授予域范围委派权限,无法模拟指定用户身份进行操作。域范围委派是Google Workspace专属功能,个人Google账号无法使用。

解决步骤

  1. 确认账号归属:你需要拥有Google Workspace(原G Suite)账号,且有域管理员权限,个人Google账号无法配置域范围委派。
  2. 启用Drive API:
    • 登录Google Cloud控制台,进入你的项目,搜索「Google Drive API」并启用。
  3. 开启服务账号的域范围委派:
    • 在Google Cloud控制台的「IAM与管理」→「服务账号」中,找到目标服务账号,进入详情页;
    • 点击「编辑」,勾选「启用G Suite域范围委派」,保存更改;
    • 返回服务账号列表,复制该账号的「客户端ID」。
  4. 在Workspace Admin后台授权API范围:
    • 登录Google Workspace Admin控制台,进入「安全」→「API控制」→「域范围委派」;
    • 点击「添加新的客户端ID」,粘贴刚才复制的客户端ID;
    • 在「OAuth范围」输入框中填入https://www.googleapis.com/auth/drive,点击「授权」。
  5. 配置文件夹权限:确保你要上传到的目标文件夹,对user_email账号开放可编辑权限。

验证代码

完成上述配置后,重新运行原代码即可实现无人值守上传,此时文件所有者会是你指定的user_email账号,文件直接存储在目标文件夹中。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.28 20:02:47