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

如何将Google Calendar接入Google Colab?解决OAuth重定向URI错误及登录凭证访问问题

连接Google Calendar到Google Colab的解决方案

一、修复OAuth重定向URI错误

要解决重定向URI错误,需在Google Cloud Console完成正确配置,步骤如下:

  • 进入你的Google Cloud项目,打开「API和服务」→「OAuth同意屏幕」,确保完成基础配置(应用名称、支持邮箱等必填项)
  • 切换到「凭据」页面,找到已创建的OAuth 2.0客户端ID,将其类型设置为桌面应用(Colab属于桌面/本地应用场景)
  • 检查该客户端ID的重定向URI列表,确保包含 http://localhost:8080/ 或 urn:ietf:wg:oauth:2.0:oob,没有的话直接添加并保存
  • 配置完成后,在Colab中使用官方库实现验证,示例代码:
!pip install --upgrade google-auth google-auth-oauthlib google-auth-httplib2 google-api-python-client

import os
from google.auth.transport.requests import Request
from google.oauth2.credentials import Credentials
from google_auth_oauthlib.flow import InstalledAppFlow
from googleapiclient.discovery import build

# 按需调整日历API权限范围,比如改为读写权限可替换为'https://www.googleapis.com/auth/calendar'
SCOPES = ['https://www.googleapis.com/auth/calendar.readonly']

creds = None
# 检查是否有已保存的凭据文件
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:
        # 先将Cloud Console下载的client_secret.json上传到Colab环境
        flow = InstalledAppFlow.from_client_secrets_file(
            'client_secret.json', SCOPES)
        creds = flow.run_local_server(port=8080)
    # 保存凭据,避免重复授权
    with open('token.json', 'w') as token:
        token.write(creds.to_json())

# 构建日历服务实例
service = build('calendar', 'v3', credentials=creds)

# 测试调用:获取主日历最近10个事件
events_result = service.events().list(calendarId='primary', 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'])

运行授权代码时,Colab会弹出授权链接,登录你的Google账号完成授权后,将页面显示的验证码输入Colab输入框即可完成验证。

二、能否绕过访问令牌直接使用登录凭证?

不行。Google Calendar API受OAuth 2.0安全机制保护,必须使用访问令牌进行身份验证,无法直接通过账号密码这类登录凭证访问。这一设计是为了避免用户凭据泄露,同时实现精细化的权限控制(比如只读、读写等不同范围)。

如果需要无交互的自动化访问,可以使用服务账号替代OAuth授权流程:

  • 在Google Cloud Console「凭据」页面创建「服务账号」,下载对应的JSON密钥文件
  • 打开目标Google Calendar的设置页面,添加服务账号的邮箱地址,分配所需权限(如编辑、只读)
  • 在Colab中使用服务账号密钥验证,示例代码:
!pip install --upgrade google-auth google-api-python-client

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

SCOPES = ['https://www.googleapis.com/auth/calendar']
# 替换为你上传的服务账号密钥文件名
SERVICE_ACCOUNT_FILE = 'service-account-key.json'

creds = service_account.Credentials.from_service_account_file(
    SERVICE_ACCOUNT_FILE, scopes=SCOPES)

service = build('calendar', 'v3', credentials=creds)

# 测试调用:创建一个测试事件
event = {
    'summary': 'Colab Test Event',
    'location': 'Online',
    'description': 'Created via service account',
    'start': {
        'dateTime': '2024-12-01T10:00:00+08:00',
        'timeZone': 'Asia/Shanghai',
    },
    'end': {
        'dateTime': '2024-12-01T11:00:00+08:00',
        'timeZone': 'Asia/Shanghai',
    },
}

event = service.events().insert(calendarId='primary', body=event).execute()
print('Event created: %s' % (event.get('htmlLink')))

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.06 19:46:01