使用Google Slides Python API编辑幻灯片遇认证范围错误求助
解决Google Slides Python API编辑时的权限范围不足问题
问题原因
你使用的presentations.readonly权限仅支持读取幻灯片数据,而batchUpdate这类编辑操作需要读写权限,因此触发了ACCESS_TOKEN_SCOPE_INSUFFICIENT错误。
解决步骤
替换权限范围
将只读权限替换为支持读写的权限:https://www.googleapis.com/auth/presentations删除旧凭证文件
必须删除项目目录下的token.json文件——该文件存储了旧权限的授权凭证,不删除的话新权限无法生效。修改代码中的SCOPES变量
把代码里的权限列表更新为新权限:SCOPES = ['https://www.googleapis.com/auth/presentations']重新运行代码完成授权
再次运行代码时,会自动弹出浏览器引导你重新授权,授权完成后会生成新的token.json,之后就能正常执行编辑操作了。
修改后的完整代码示例
from __future__ import print_function 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 import os.path from googleapiclient.errors import HttpError import json # 替换为读写权限,修改后需删除token.json SCOPES = ['https://www.googleapis.com/auth/presentations'] # 你的演示文稿ID PRESENTATION_ID = 'LEWL' creds = None # token.json存储用户的访问和刷新令牌,首次授权后自动生成 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( 'credentials.json', SCOPES) creds = flow.run_local_server(port=0) # 保存新凭证供下次使用 with open('token.json', 'w') as token: token.write(creds.to_json()) service = build('slides', 'v1', credentials=creds) # 在索引1位置添加使用预定义布局的幻灯片 requests = [ { 'createSlide': { 'objectId': 'titlepage', 'insertionIndex': '1', 'slideLayoutReference': { 'predefinedLayout': 'TITLE_AND_TWO_COLUMNS' } } } ] # 执行批量更新请求 body = { 'requests': requests } response = service.presentations() \ .batchUpdate(presentationId=PRESENTATION_ID, body=body).execute() create_slide_response = response.get('replies')[0].get('createSlide') print(f"Created slide with ID:" f"{(create_slide_response.get('objectId'))}")
内容的提问来源于stack exchange,提问作者Mohit Reddy
相关产品推荐
相关产品推荐

