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

为何Google Colab中auth.authenticate_user()无法访问个人Google Calendar?

解决Google Colab访问个人Google Calendar API的权限问题

问题根源

你当前代码里的google.auth.default()获取的是Colab环境的默认服务账号凭据(显示为default),这类凭据仅能访问关联Google Cloud项目的资源,没有权限访问你的个人Google日历——个人日历属于用户私有数据,必须通过OAuth 2.0用户授权流程获取凭据才能访问。

解决方案步骤

1. 准备OAuth客户端凭据

  • 登录Google Cloud Console,创建或选择你的项目,启用Google Calendar API。
  • 进入「API和服务」→「凭据」页面,创建「OAuth客户端ID」,应用类型选择「桌面应用」。
  • 下载生成的credentials.json文件。

2. Colab中实现授权与访问

替换原有代码,使用以下逻辑:

from googleapiclient.discovery import build
from google_auth_oauthlib.flow import InstalledAppFlow
import datetime

# 定义所需权限
SCOPES = ['https://www.googleapis.com/auth/calendar.readonly']

# 加载OAuth客户端凭据
flow = InstalledAppFlow.from_client_secrets_file('credentials.json', SCOPES)
# Colab无本地浏览器,使用控制台授权流程
creds = flow.run_console()

# 构建Calendar服务
service = build("calendar", "v3", credentials=creds)

# 获取近期事件
now = datetime.datetime.now(tz=datetime.timezone.utc).isoformat() + "Z"
events_result = (
    service.events()
    .list(
        calendarId="primary",
        timeMin=now,
        maxResults=10,
        singleEvents=True,
        orderBy="startTime",
    )
    .execute()
)

events = events_result.get('items', [])
if not events:
    print('No upcoming events found.')
for event in events:
    start = event['start'].get('dateTime', event['start'].get('date'))
    print(start, event['summary'])

3. 执行时的操作

运行代码后,Colab会输出一个授权链接:

Please visit this URL to authorize this application: https://accounts.google.com/o/oauth2/auth?xxx

复制该链接到本地浏览器打开,用你的个人Google账号登录并授权,页面会生成一个授权码。将授权码粘贴回Colab的输入框并回车,即可完成授权。

关键说明

  • auth.authenticate_user()仅适用于访问Google Cloud Storage、BigQuery等与项目绑定的云资源,无法用于访问个人用户的Calendar、Drive等私有数据。
  • run_console()是为无浏览器环境设计的OAuth授权方式,完美适配Colab的运行环境。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.12 09:22:45