python - 如何从 Python 脚本向 Google App Script API 传递参数?

标签 python python-3.x google-apps-script google-api-python-client google-apps-script-api

我有一个参数 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

Google 应用脚本的功能:

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 从 shell 传递到 Google 应用脚本进行处理。谢谢!

最佳答案

official documentation 中所写, 你必须在请求正文中提供:

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

也可以使用setValue(e.salesID);

关于python - 如何从 Python 脚本向 Google App Script API 传递参数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54818256/

相关文章:

javascript - Google 表格有条件地组合,清除范围内的所有单元格,循环。 VBA转JS

google-apps-script - Google App Script Web App 上的并发点击或同时执行的数量是否有限制

python - 在字典中保留重复键的最高值

python - 根据 pandas 中每个排序组的第一行创建一列

python - 尝试在 Python 中检索事件监视器 ID

python - numpy中不同长度数组的数组比较

Python Tkinter : How do you create a toplevel window and destroy the previous window?

regex - 谷歌应用程序脚本 : REGEX to fix malformed pipe delimited csv file runs too slowly

python - 如何清除YouTube视频下载器中的 'cipher'错误并以mp3格式下载视频?

python - 为什么 scipy 稀疏矩阵内存使用对矩阵中元素的数量无动于衷?