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

时间:2019-02-23 04:30:47

标签: python google-api-python-client oauth2client google-apps-script-api

我几乎使用了Google自己的网站中的示例

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方面的问题,因为即使他们的示例代码也不起作用。

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

2 个答案:

答案 0 :(得分:1)

根据您的情况,有两种模式。

模式1:

使用authorization script at Quickstart

示例脚本:

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上对此进行了讨论。

示例脚本:

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
}

注意:

在我的环境中,我可以确认以上两种模式都可以使用。但是,如果您的环境中没有使用这些功能,我深表歉意。

答案 1 :(得分:0)

我遇到了同样的错误。

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

但是突然之间,自2月23日以来我一直无法使用。

所以我采用了另一种方法,并且在oauth2中使用了post request。

我认为您需要续订Google服务帐户。

我认为范围ui会有所改变...

祝你好运!

■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代码并发布为网络应用。

■Google Apps脚本代码

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