无法访问 Google Execution API 并收到 500 内部错误

问题描述 投票:0回答:1

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

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

***更新:使用 OAuth2 用户客户端 ID 时,我已通过教程脚本成功访问了执行 API。 使用服务帐户连接到执行 API 是否仍然存在问题?

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

/**
   * 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'
python google-apps-script http-status-code-500 google-apps-script-api
1个回答
1
投票

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

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

所以现在,我建议使用 2 个帐户来访问带有服务帐户的 google Sheets api 和带有 OAuth2 客户端 ID 的执行 api

© www.soinside.com 2019 - 2024. All rights reserved.