如何从Python脚本向Google App Script API传递参数? [英] How can I pass an argument to Google App Script API from Python script?

本文介绍了如何从Python脚本向Google App Script API传递参数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个参数SalesID,我想传递给Google App脚本.如何使用此python脚本传递它?

I have an argument SalesID I'd like to pass through to the Google App Script. How can I pass it through with this python script?

(脚本来自 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

Sample Google Sheet: https://docs.google.com/spreadsheets/d/1Z4PAY3CCaRorn5LRdFQKn4-EcAHxwxHJsABzEgsSQk0/edit#gid=0

Google应用脚本的功能:

Google app script's function:

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);
}

基本上,我希望能够将SalesID从外壳传递到Google应用程序脚本进行处理.谢谢!

Basically I'd like to be able to pass the SalesID from shell to Google app script to process. Thanks!

推荐答案

As written in the official documentation, You must provide it in the request body:

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

也使用setValue(e.salesID);

这篇关于如何从Python脚本向Google App Script API传递参数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆