如何通过Python API为部署Apps Script授权Google Sheets OAuth权限
我用Python调用Google API创建以Google Sheets为父级的Apps Script,脚本会向父表格写入数据。但通过API部署时一直收到“Requested entity was not found”错误。后来发现手动在网页部署时,得先给脚本授权访问Google Sheets的OAuth权限,授权后API部署就能成功。
附上我的Python代码:
# Import required libraries from googleapiclient.discovery import build from google.oauth2 import service_account # Define your credentials credentials = service_account.Credentials.from_service_account_file('path/to/credentials.json') scopes = ['https://www.googleapis.com/auth/spreadsheets', 'https://www.googleapis.com/auth/script.projects', 'https://www.googleapis.com/auth/script.deployments' ] # Build the API service service = build('script', 'v1', credentials=credentials) def create_script(sheet_id): # Create a new Apps Script project request = service.projects().create( body={ 'title': 'My App Script', 'parentId': sheet_id } ) response = request.execute() script_id = response['scriptId'] script_code= '''function addRowToSheet() { var sheet = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet(); var newRowData = ['Value 1', 'Value 2', 'Value 3']; sheet.appendRow(newRowData); }''' request = { 'files': [ { 'name': 'Code', 'type': 'SERVER_JS', 'source': script_code }, { 'name': 'appsscript', 'type': 'JSON', 'source': {}.strip() } ] } create_file_request = service.projects().updateContent( scriptId=script_id, body=request ).execute() return script_id def deploy_script(script_id ): # Deploy the Apps Script request = service.projects().deployments().create( scriptId=script_id , # Replace with the ID of your Apps Script body={ 'scriptId': script_id, 'versionNumber': 1, 'manifestFileName': 'appsscript' } ) response = request.execute() deployment_id = response['deploymentId']
我的问题:怎么直接通过API代码授予所需的OAuth权限?我有具备必要权限的令牌,或者怎么引导用户用Google账户认证给项目授权?
一、通过API处理权限(服务账号场景)
服务账号本身无法直接为Apps Script项目绑定用户级OAuth权限,但可以通过以下方式适配:
启用域范围授权(仅限Google Workspace域)
如果你使用的是Workspace域内的服务账号,可设置域范围授权让服务账号模拟域内用户操作:- 在Google Cloud Console找到服务账号,进入「高级设置」启用域范围授权。
- 登录Workspace Admin控制台,在「API控件」中添加服务账号的客户端ID,并授予所需的OAuth scopes(
https://www.googleapis.com/auth/spreadsheets、https://www.googleapis.com/auth/script.projects等)。 - 修改代码中凭据初始化部分,指定要模拟的域内用户邮箱:
credentials = service_account.Credentials.from_service_account_file( 'path/to/credentials.json', scopes=scopes, subject="user@yourdomain.com" # 替换为实际域内用户邮箱 )
完善Apps Script清单配置
你当前的appsscript.json是空的,需要明确声明权限范围,让部署流程识别权限需求。修改updateContent中的清单文件:{ 'name': 'appsscript', 'type': 'JSON', 'source': '''{ "timeZone": "Asia/Shanghai", "dependencies": {}, "exceptionLogging": "STACKDRIVER", "oauthScopes": [ "https://www.googleapis.com/auth/spreadsheets.currentonly", "https://www.googleapis.com/auth/script.projects" ] }''' }用
spreadsheets.currentonly可避免过度授权,仅允许访问父级表格。
二、引导用户完成OAuth授权(普通Google账户场景)
面向普通个人账户时,需要让用户手动完成OAuth授权流程:
切换到OAuth2客户端ID认证
放弃服务账号,改用OAuth2客户端ID(在Google Cloud Console的「API和服务」→「凭据」中创建「桌面应用」或「Web应用」类型的客户端ID),并使用google-auth-oauthlib库处理授权:from google_auth_oauthlib.flow import InstalledAppFlow flow = InstalledAppFlow.from_client_secrets_file( 'path/to/client_secret.json', scopes=scopes ) credentials = flow.run_local_server(port=0)运行代码时会自动打开浏览器,引导用户登录Google账户并授权,授权凭据会自动缓存,后续可直接复用。
触发首次权限验证
即使通过API部署成功,脚本首次执行时仍需用户授权。可以:- 引导用户打开Apps Script编辑器,手动运行一次
addRowToSheet函数,触发权限提示; - 通过API调用脚本的
run方法,强制触发授权流程(需用户交互)。
- 引导用户打开Apps Script编辑器,手动运行一次
三、排查“Requested entity was not found”错误
除权限外,该错误还可能由以下原因导致:
- 确认
sheet_id正确,且服务账号/授权用户对目标Sheet拥有编辑权限; - 检查Google Cloud Console中是否已启用Apps Script API;
- 确保部署时的
manifestFileName与上传的清单文件名一致(当前代码中为appsscript,无问题)。
内容的提问来源于stack exchange,提问作者nerya

