我该如何在Python脚本中向Google App Script API传递参数?

3
我有一个参数SalesID,我想将其传递给Google App Script。如何使用此Python脚本传递它?
(脚本来自https://developers.google.com/apps-script/api/how-tos/execute
from __future__ import print_function
from googleapiclient import errors
from googleapiclient.discovery import build
from httplib2 import Http
from oauth2client import file as oauth_file, client, tools

def main(SalesID):
    """Runs the sample.
    """
    SCRIPT_ID = '1WChnVrk5gycQEtumI7mPi5PexXafuhBAWN7-VnBK2aPkFpzMHtUp0cnx' #Actual Google Sheet Sample

    # Setup the Apps Script API
    SCOPES = ['https://www.googleapis.com/auth/script.projects','https://www.googleapis.com/auth/spreadsheets']
    store = oauth_file.Storage('token.json')
    creds = store.get()
    if not creds or creds.invalid:
        flow = client.flow_from_clientsecrets('credentials.json', SCOPES)
        creds = tools.run_flow(flow, store)
    service = build('script', 'v1', http=creds.authorize(Http()))

    # 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 depends 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.iteritems():
                    print("\t{0} ({1})".format(folder, folderId))

    except errors.HttpError as e:
        # The API encountered a problem before the script started executing.
        print(e.content)


if __name__ == '__main__':
    main()

示例Google表格:https://docs.google.com/spreadsheets/d/1Z4PAY3CCaRorn5LRdFQKn4-EcAHxwxHJsABzEgsSQk0/edit#gid=0

谷歌应用脚本的功能:

function myFunction(e) {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getSheetByName("Sheet1");
var timestamp = new Date();

sheet.getRange("A2").setValue(e.parameter.SalesID);
sheet.getRange("B2").setValue(timestamp);
}

基本上,我希望能够从 shell 传递 SalesID 到 Google 应用脚本进行处理。谢谢!
1个回答

3

官方文档所述,您必须在请求正文中提供它:

request = {"function": "myFunction", "parameters": [{"salesID" : 123}]}

还要使用 setValue(e.salesID);


1
@sojim2 考虑到你已经自己阅读并理解了 jwt OAuth 文档,我相信你很快就能弄清楚它。 - TheMaster
1
例如,您可以尝试在Drive API的快速入门中使用授权脚本。在我的环境中,我已经确认我使用了这个脚本来调用Apps Script API,并且它有效。https://developers.google.com/drive/api/v3/quickstart/python - Tanaike
1
@sojim2,很高兴你的问题得到了解决。有几个授权脚本可供使用。所以当其中一个无法使用时,其他脚本就可以使用。这是其中之一。顺便问一下,你能否把完成的脚本添加到你发布的GitHub问题中呢?我认为它可能对其他用户有用。 - Tanaike
1
@TheMaster 我也这么认为。 - Tanaike
1
@Tanaike @TheMaster 看起来最近其他人也遇到了同样的问题 https://github.com/googleapis/google-api-python-client/issues/628。他们已经有了解决方法,但这不是长期解决方案,因为oAuth2client已被弃用。解决方案是:`service = build('script', 'v1', credentials=creds)`。 - sojim2
显示剩余5条评论

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接