无法访问谷歌执行 API 并收到 500 内部错误



我在APPS脚本中创建了一个脚本,并将其部署为API可执行文件。连接到它时,我开始收到500错误。我决定从教程创建一个脚本来定位此错误的问题。令我惊讶的是,我收到了相同的结果。问题可能出在服务帐户上,因为我将脚本与我拥有服务帐户的项目相关联,并尝试使用它进行授权。

我读到使用服务帐户连接到执行 API 存在问题,今天仍然如此。

更新:使用 OAuth2 用户客户端 ID 时,我已成功访问带有教程脚本的执行 API。 使用服务帐户连接到执行 API 是否仍有任何问题?

这是我作为 API 可执行文件部署到我拥有服务帐户的项目的应用程序脚本:

/**
* The function in this script will be called by the Apps Script Execution  API.    */
/**
* Return the set of folder names contained in the user's root folder as an
* object (with folder IDs as keys).
* @return {Object} A set of folder names keyed by folder ID.
*/
function getFoldersUnderRoot() {
var root = DriveApp.getRootFolder();
var folders = root.getFolders();
var folderSet = {};
while (folders.hasNext()) {
var folder = folders.next();
folderSet[folder.getId()] = folder.getName();
}
return folderSet;
}

这是我从教程中获取的部分修改代码。我将其更改为使用服务帐户:

from googlepackage.api_client import *
from googlepackage.constants import *
from googleapiclient.errors import HttpError
from httplib2 import Http

def __get_credentials(scopes: list) -> ServiceAccountCredentials:
credential_dir = os.path.join("..\", SERVICE_ACCOUNT_FOLDER)
print(credential_dir)
if not os.path.exists(credential_dir):
raise Exception("Cannot find the directory with credentials")
try:
credentials = ServiceAccountCredentials.from_json_keyfile_name(
os.path.join(credential_dir, 'file.json'),
scopes)
except (ValueError, KeyError) as error:
raise Exception(error)
return credentials

def main():
"""Shows basic usage of the Apps Script Execution API.
Creates a Apps Script Execution API service object and uses it to call an
Apps Script function to print out a list of folders in the user's root
directory.
"""
SCRIPT_ID = 'API ID'
http_auth = __get_credentials([READ_AND_WRITE_SCOPE, DRIVE_API_SCOPE]).authorize(Http())
# Authorize and create a service object.
service = discovery.build('script', 'v1', http=http_auth)
# Create an execution request object.
request = {"function": "getFoldersUnderRoot"}
try:
# Make the API request.
response = service.scripts().run(body=request, scriptId=SCRIPT_ID).execute()
if 'error' in response:
# The API executed, but the script returned an error.
# Extract the first (and only) set of error details. The values of
# this object are the script's 'errorMessage' and 'errorType', and
# an list of stack trace elements.
error = response['error']['details'][0]
print("Script error message: {0}".format(error['errorMessage']))
if 'scriptStackTraceElements' in error:
# There may not be a stacktrace if the script didn't start
# executing.
print("Script error stacktrace:")
for trace in error['scriptStackTraceElements']:
print("t{0}: {1}".format(trace['function'],
trace['lineNumber']))
else:
# The structure of the result will depend upon what the Apps Script
# function returns. Here, the function returns an Apps Script Object
# with String keys and values, and so the result is treated as a
# Python dictionary (folderSet).
folderSet = response['response'].get('result', {})
if not folderSet:
print('No folders returned!')
else:
print('Folders under your root folder:')
for (folderId, folder) in folderSet.items():
print("t{0} ({1})".format(folder, folderId))
except HttpError as e:
# The API encountered a problem before the script started executing.
print(e.content)
if __name__ == '__main__':
main()

以下是我的回复中的HttpError内容:

b'{n  "error": {n    "code": 500,n    "message": "Internal error 
encountered.",n    "errors": [n      {n        "message": "Internal error 
encountered.",n        "domain": "global",n        "reason": 
"backendError"n      }n    ],n    "status": "INTERNAL"n  }n}n'

更新:使用 OAuth2 用户客户端 ID 时,我已成功访问带有教程脚本的执行 API。

我仍然无法使用服务帐户及其凭据执行 api。 我只能使用 OAuth2 客户端 ID 连接到执行 API。

所以现在,我建议使用 2 个帐户访问带有服务帐户的谷歌表格 API 和具有 OAuth2 客户端 ID 的执行 API

相关内容

  • 没有找到相关文章

最新更新