Google App Script API无法验证“请求包含无效参数”

问题描述 投票:2回答:2

我几乎使用谷歌自己的网站上的样本

https://developers.google.com/apps-script/api/how-tos/execute

下面复制了示例python脚本的相关部分

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():
    """Runs the sample.
    """
    SCRIPT_ID = 'ENTER_YOUR_SCRIPT_ID_HERE'

    # Setup the Apps Script API
    SCOPES = 'https://www.googleapis.com/auth/script.projects'
    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()))


if __name__ == '__main__':
    main()

我收到以下错误

  File "test.py", line 67, in <module>
    main()
  File "test.py", line 22, in main
    service = build('script', 'v1', http=creds.authorize(Http()))
  File "C:\Users\pedxs\Anaconda2\lib\site-packages\googleapiclient\_helpers.py", line 130, in positional_wrapper
    return wrapped(*args, **kwargs)
  File "C:\Users\pedxs\Anaconda2\lib\site-packages\googleapiclient\discovery.py", line 232, in build
    raise e
googleapiclient.errors.HttpError: <HttpError 400 when requesting https://www.googleapis.com/discovery/v1/apis/script/v1/rest returned "Request contains an invalid argument.">

一周前,我有这个确切的代码工作。第22行使用发现构建功能,据我所知,它正在向Google的API身份验证服务器“https://www.googleapis.com/discovery/v1/apis/script/v1/rest”发送凭据。我怀疑这是谷歌方面的问题,因为即使他们的示例代码也不起作用。

我尝试创建一个新的Google Cloud Platform并获取一个新的credentials.json文件。我还尝试使用其他电子邮件帐户进行身份验证。

python google-api-python-client oauth2client google-apps-script-api
2个回答
1
投票

在您的情况下,有2种模式。

模式1:

使用authorization script at Quickstart

Sample script:

from __future__ import print_function
import pickle
import os.path
from googleapiclient.discovery import build
from google_auth_oauthlib.flow import InstalledAppFlow
from google.auth.transport.requests import Request

def main():
    # Setup the Apps Script API
    SCOPES = ['https://www.googleapis.com/auth/script.projects', 'https://www.googleapis.com/auth/drive']

    creds = None
    if os.path.exists('token.pickle'):
        with open('token.pickle', 'rb') as token:
            creds = pickle.load(token)
    if not creds or not creds.valid:
        if creds and creds.expired and creds.refresh_token:
            creds.refresh(Request())
        else:
            flow = InstalledAppFlow.from_client_secrets_file(
                'client_secret.json', SCOPES)
            creds = flow.run_local_server()
        with open('token.pickle', 'wb') as token:
            pickle.dump(creds, token)
    service = build('script', 'v1', credentials=creds)

    scriptId = "### script ID ###"  # Please set this
    request = {"function": "myFunction", "parameters": ["sample"], "devMode": True}
    response = service.scripts().run(body=request, scriptId=scriptId).execute()
    print(response)


if __name__ == '__main__':
    main()

模式2:

如果您想在问题中使用该脚本,请按如下方式修改您的脚本。这在herehere进行了讨论。

Sample script:

from __future__ import print_function
from googleapiclient.discovery import build
from oauth2client import file as oauth_file, client, tools

def main():
    SCOPES = ['https://www.googleapis.com/auth/script.projects', 'https://www.googleapis.com/auth/drive']

    store = oauth_file.Storage('token.json')
    creds = store.get()
    if not creds or creds.invalid:
        flow = client.flow_from_clientsecrets('client_secret.json', SCOPES)
        creds = tools.run_flow(flow, store)
    service = build('script', 'v1', credentials=creds)

    scriptId = "### script ID ###"  # Please set this
    request = {"function": "myFunction", "parameters": ["sample"], "devMode": True}
    response = service.scripts().run(body=request, scriptId=scriptId).execute()
    print(response)


if __name__ == '__main__':
    main()

GAS方面的示例脚本:

function myFunction(e) {
  return "ok: " + e;
}

结果:

您可以从上面的两个脚本中检索以下响应。

{
  "response": {
    "@type": "type.googleapis.com/google.apps.script.v1.ExecutionResponse",
    "result": "ok: sample"
  },
  "done": True
}

注意:

在我的环境中,我可以确认以上两种模式都可以使用。但是,如果在你的环境中,那些没有使用,我道歉。


0
投票

我遇到了同样的错误。

我在一年多前使用过该代码。

但是从2月23日开始我突然无法使用。

所以我采用了另一种方法,并使用了oauth2的post请求。

我认为你需要续订谷歌服务帐户。

我觉得有些东西会随着范围发生变化...

祝好运!

■python代码

from oauth2client import client

def request_to_gas():
    credentials = client.OAuth2Credentials(
        access_token=None,
        client_id={your_client_id},
        client_secret={your_client_secret},
        refresh_token={your_refresh_token},
        token_expiry=None,
        token_uri=GOOGLE_TOKEN_URI,
        user_agent=None,
        revoke_uri=GOOGLE_REVOKE_URI)

    credentials.refresh(httplib2.Http())  # refresh the access token


    my_url = "your_google_apps_script_web_url" 
    myheaders = {'Authorization': 'Bearer {}'.format(credentials.access_token),
                 "Content-Type": "application/json"
                 }
    response = requests.post(my_url,
                  data=json.dumps({
                                   'localdate' : '2019/02/23 12:12:12'}),
                  headers=myheaders
                  )

添加thins代码并发布为Web应用程序。

■谷歌应用程序脚本代码

function doPost(e) {
  var params = JSON.parse(e.postData.getDataAsString());  // ※
  var value = params.localdate;  // get python code -- 2019/02/23 12:12:12

  // here is your google apps script api
  do_something();

  var output = ContentService.createTextOutput();
  output.setMimeType(ContentService.MimeType.JSON);
  output.setContent(JSON.stringify({ message: "success!" }));

  return output;
}
© www.soinside.com 2019 - 2024. All rights reserved.