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

如何用Python实现无需手动OAuth登录自动上传文件至Google Drive

实现PyDrive无手动登录自动上传Google Drive

关键问题分析

你的配置存在拼写错误,且需要完成仅一次的手动授权流程生成持久化凭证文件,之后脚本即可自动运行。

步骤1:修正settings.yaml的拼写错误

settings.yaml中cient_config_backend拼写有误,需改为client_config_backend,修正后的完整配置如下:

client_config_backend: settings
client_config:
  client_id: some_client_id
  client_secret: some_client_secret

save_credentials: True
save_credentials_backend: file
save_credentials_file: credentials.json
#save_credentials_file: client_secrets.json

get_refresh_token: True

oauth_scope:
  - https://www.googleapis.com/auth/drive.file
  - https://www.googleapis.com/auth/drive.install

步骤2:完成首次手动授权(仅需一次)

运行现有代码,此时会弹出浏览器要求登录Google账户并完成授权。授权成功后,脚本会在当前目录自动生成credentials.json文件——该文件包含刷新令牌,后续运行脚本时会自动用它获取新的访问令牌,无需再手动登录。

步骤3:调整代码确保自动加载凭证

修改代码,明确指定配置文件路径,并处理凭证的加载、刷新逻辑:

from pydrive.auth import GoogleAuth
from pydrive.drive import GoogleDrive

# 初始化认证,指定settings.yaml路径(同目录可省略,显式指定更稳妥)
gauth = GoogleAuth(settings_file='settings.yaml')
# 尝试加载已保存的凭证
gauth.LoadCredentialsFile("credentials.json")

if gauth.credentials is None:
    # 首次运行触发授权流程
    gauth.LocalWebserverAuth()
elif gauth.access_token_expired:
    # 凭证过期自动刷新
    gauth.Refresh()
else:
    # 有效凭证直接完成授权
    gauth.Authorize()

# 保存更新后的凭证(如有)
gauth.SaveCredentialsFile("credentials.json")

drive = GoogleDrive(gauth)
file1 = drive.CreateFile()
file1.SetContentFile('/home/Desktop/file.xml')
file1.Upload()
print("文件上传完成")

后续自动运行

完成首次授权后,每次运行上述脚本都会自动加载credentials.json中的刷新令牌,无需手动操作即可完成上传。你可以配合系统定时任务(如Linux的cron、Windows的任务计划程序)实现每日自动执行。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.22 14:06:25