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

如何正确配置Google Drive API凭证以在Jupyter Notebook下载文件?

解决Jupyter Notebook中Google Drive API凭证配置与认证报错问题

一、修正OAuth 2.0凭证类型配置

你当前选择的Web Application类型不适合本地Jupyter环境,更简单的方案是切换为Desktop app(桌面应用)类型:

  • 进入Google Cloud Console的凭证页面,删除现有Web类型凭证,重新创建Desktop app类型的OAuth客户端ID
  • 创建完成后下载client_secret.json到Jupyter工作目录,该类型凭证会自动配置好redirect_uris,无需手动填写,直接就能解决Missing property "redirect_uris"错误

如果坚持使用Web Application类型,需手动配置:

  • JavaScript authoritative sources:填写Jupyter Notebook的访问地址,比如默认的http://localhost:8888
  • Authorized redirect URIs:添加代码中指定的端口地址:http://localhost:8080/和http://localhost:8090/,保存后重新下载client_secret.json

二、替换过时的认证代码(原教程依赖已废弃)

原教程使用的oauth2client库已被Google官方弃用,需更换为最新的认证库:

  1. 卸载旧依赖
pip uninstall -y oauth2client
  1. 安装新依赖
pip install google-auth google-auth-oauthlib google-auth-httplib2 google-api-python-client
  1. 使用最新认证代码替换原代码:
from google.oauth2.credentials import Credentials
from google_auth_oauthlib.flow import InstalledAppFlow
from google.auth.transport.requests import Request
import os

# 权限范围,只读足够下载文件
SCOPES = ['https://www.googleapis.com/auth/drive.readonly']

creds = None
# 检查是否已有保存的token
if os.path.exists('token.json'):
    creds = Credentials.from_authorized_user_file('token.json', SCOPES)

# 如果没有有效凭证,触发认证流程
if not creds or not creds.valid:
    if creds and creds.expired and creds.refresh_token:
        creds.refresh(Request())
    else:
        flow = InstalledAppFlow.from_client_secrets_file(
            'client_secret.json', SCOPES)
        # 启动本地服务器完成认证
        creds = flow.run_local_server(port=8080)
    # 保存token供下次使用
    with open('token.json', 'w') as token:
        token.write(creds.to_json())

三、测试文件下载(示例)

认证完成后,可使用以下代码测试下载Google Drive文件:

from googleapiclient.discovery import build
from googleapiclient.http import MediaIoBaseDownload
import io

# 构建Drive服务
service = build('drive', 'v3', credentials=creds)

# 替换为你的文件ID(从Drive文件链接中提取)
file_id = '你的Google Drive文件ID'
request = service.files().get_media(fileId=file_id)
# 下载到内存
fh = io.BytesIO()
downloader = MediaIoBaseDownload(fh, request)
done = False
while done is False:
    status, done = downloader.next_chunk()
    print(f"下载进度: {int(status.progress() * 100)}%")

# 将内容写入本地文件
fh.seek(0)
with open('下载的文件名.ext', 'wb') as f:
    f.write(fh.read())

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.26 18:47:22