我在APPS脚本中创建了一个脚本,并将其部署为API Executable。连接时我开始遇到500错误。我决定从教程创建一个脚本来解决此错误的问题。令我惊讶的是,我收到了同样的结果。可能问题在于服务帐户,因为我将脚本与我拥有服务帐户的项目相关联,并尝试使用它进行授权。
我读到使用服务帐户连接到Execution API时出现问题,今天仍然可以这样。
***更新:使用OAuth2用户客户端ID时,我已成功使用教程脚本访问了Execution API。 使用服务帐户连接到Execution API仍有问题吗?
以下是我作为API Executable部署到我拥有服务帐户的项目的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'
答案 0 :(得分:0)
更新:使用OAuth2用户客户端ID时,我已使用教程脚本成功访问了Execution API。
我仍然无法使用服务帐户及其凭据来执行api。 我只能使用OAuth2客户端ID连接到Execution API。
所以现在,我建议使用2个帐户访问带有服务帐户的google sheet api和带有OAuth2客户端ID的执行api