Python Google应用程序脚本API无法进行身份验证;请求包含无效的参数";

Python Google应用程序脚本API无法进行身份验证;请求包含无效的参数";,python,google-api-python-client,oauth2client,google-apps-script-api,Python,Google Api Python Client,Oauth2client,Google Apps Script Api,我基本上使用的是谷歌自己网站上的样本 下面复制了示例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 ma

我基本上使用的是谷歌自己网站上的样本

下面复制了示例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.">
文件“test.py”,第67行,在
main()
文件“test.py”,第22行,在main中
service=build('script','v1',http=creds.authorize(http()))
文件“C:\Users\pedxs\Anaconda2\lib\site packages\googleapiclient\\u helpers.py”,第130行,在位置包装中
已包装退货(*args,**kwargs)
文件“C:\Users\pedxs\Anaconda2\lib\site packages\googleapiclient\discovery.py”,第232行,内部版本
提高e
GoogleAppClient.errors.HttpError:
一周前,我的代码还在工作。第22行使用了发现构建函数,据我所知,该函数正在向Google的API身份验证服务器“”发送凭据。我怀疑这是谷歌方面的一个问题,因为即使是他们的示例代码也不起作用


我尝试创建一个新的谷歌云平台,并获得一个新的credentials.json文件。我还尝试使用不同的电子邮件帐户进行身份验证。

我遇到了相同的错误

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

但是突然间,我从2月23日起就不能使用了

因此,我采用了另一种方法,并将post请求与oauth2一起使用

我想你需要更新你的谷歌服务帐户

我认为随着用户界面的变化,有些东西会改变

祝你好运

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

在您的情况下,有两种模式

模式1: 使用

示例脚本: 模式2: 如果您想在问题中使用脚本,请按以下方式修改脚本。这将在和中讨论

示例脚本: 气体侧的样本脚本: 结果: 您可以从以上两个脚本中检索以下响应

{
  "response": {
    "@type": "type.googleapis.com/google.apps.script.v1.ExecutionResponse",
    "result": "ok: sample"
  },
  "done": True
}
注:
  • 在使用上述脚本之前,请先进行设置以使用它。你可以在下面看到官方文件。

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

我认为这可能对您的情况有用@塔奈克。那么,这种身份验证方法似乎不再有效了?你找到了另一种有效的方法吗?有几种方法。1.在上使用授权脚本。2.如果要在问题中使用脚本,请从
http=credentials.authorize(httplib2.http())
service=discovery.build('script','v1',http=http)
修改为
service=build('script','v1',credentials=creds)
。这是在和上讨论的。我的问题与原来的问题完全相同。我的脚本已经运行了将近2年,现在我得到了同样的错误,没有做任何其他更改。谷歌方面有什么变化吗?@Tanaike你应该发布一个答案这为我解决了这个问题,关键是将凭据传递给build(),而不是授权的http对象。令人惊讶的是,这真是太棒了,伙计!
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
}