Google Calendar API Python:无法删除群组日历事件
解决Google Calendar API删除群组日历事件的401未授权问题
你的代码核心问题在于删除事件时直接使用requests.delete()发送请求,但这个请求没有携带OAuth2认证凭证。虽然你已经通过credentials.authorize(httplib2.Http())获取了授权的HTTP客户端并构建了Calendar服务对象,但requests库和这个授权客户端完全无关,导致API请求因缺少认证信息返回401错误。而你能正常创建事件,应该是创建逻辑用了service对象的方法(自动携带认证),和删除的错误逻辑形成对比。
修正方案
直接使用Google Calendar API提供的Python客户端库方法执行删除操作,无需手动调用requests。修改后的代码如下:
from __future__ import print_function import httplib2 import os from apiclient import discovery from oauth2client import file import oauth2client from oauth2client import client from oauth2client import tools import datetime SCOPES = 'https://www.googleapis.com/auth/calendar' CLIENT_SECRET_FILE = 'credentials.json' APPLICATION_NAME = 'Google Calendar API Python Quickstart' calendar_use = 'XXXXXXX@group.calendar.google.com' def get_credentials(): """Gets valid user credentials from storage. If nothing has been stored, or if the stored credentials are invalid, the OAuth2 flow is completed to obtain the new credentials. Returns: Credentials, the obtained credential. """ home_dir = os.path.expanduser('~') credential_dir = os.path.join(home_dir, '.credentials') if not os.path.exists(credential_dir): os.makedirs(credential_dir) credential_path = os.path.join(credential_dir,'calendar-python-quickstart.json') store = oauth2client.file.Storage(credential_path) credentials = store.get() if not credentials or credentials.invalid: flow = client.flow_from_clientsecrets(CLIENT_SECRET_FILE, SCOPES) flow.user_agent = APPLICATION_NAME try: import argparse flags = argparse.ArgumentParser(parents=[tools.argparser]).parse_args() except ImportError: flags = None if flags: credentials = tools.run_flow(flow, store, flags) else: # Needed only for compatibility with Python 2.6 credentials = tools.run(flow, store) print('Storing credentials to ' + credential_path) return credentials def deleteEvent(): credentials = get_credentials() http = credentials.authorize(httplib2.Http()) service = discovery.build('calendar', 'v3', http=http) # 使用API客户端库的delete方法,自动携带认证 event_id = 'xxxxxxxxxxxxxxxxx' # 替换为你的事件ID service.events().delete( calendarId=calendar_use, eventId=event_id ).execute() print("事件删除成功") deleteEvent()
关键修改点
- 移除了无用的
requests库导入 - 删除事件时使用
service.events().delete()方法,传入群组日历ID和目标事件ID,该方法会自动使用已授权的HTTP客户端发送请求,无需手动处理认证头 - 补充了
flags的初始化逻辑(原代码中flags变量未定义,可能导致额外报错)
内容的提问来源于stack exchange,提问作者Aragor
相关产品推荐
相关产品推荐

