Google App Script API 无法对"Request contains an invalid argument"进行身份验证



我几乎正在使用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:UserspedxsAnaconda2libsite-packagesgoogleapiclient_helpers.py", line 130, in positional_wrapper
    return wrapped(*args, **kwargs)
  File "C:UserspedxsAnaconda2libsite-packagesgoogleapiclientdiscovery.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行使用Discovery Build函数,据我所知,该功能将凭据发送到Google的API Authenticator Server" https://www.googleapis.com/discovery/v1/apis/script/script/v1/rest"。我怀疑这在Google方面是一个问题,因为即使它们的示例代码也不起作用。

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

我遇到相同的错误。

我已经在1年前使用了该代码。

,但突然我从2月23日起就无法使用。

所以我采用了另一种方法,然后使用oauth2使用了邮政请求。

我认为您需要续订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
                  )

添加Tinins代码并以Web应用程序发布。

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

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

模式1:

在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:

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

示例脚本:

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()

气体脚本的示例脚本:

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

结果:

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

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

注意:

  • 在使用上述脚本之前,请设置使用它。您可以在下面查看官方文件。
    • 使用应用程序脚本API
    • 执行函数
    • 方法:scripts.run

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

相关内容

  • 没有找到相关文章

最新更新