我正在从笔记本电脑上运行此代码。我想在GCP上调用一个tensorlflow模型。我尝试模拟从我们的系统到GCP的API调用。
from oauth2client.client import GoogleCredentials
import requests
import json
PROJECT = 'blabla-project'
MODEL_NAME = 'blablaModelName'
MODEL_VERSION = 'blabla_version'
token=GoogleCredentials.get_application_default().get_access_token().access_token
api = 'https://ml.googleapis.com/v1/projects/{}/models/{}/versions/{}:predict' \
.format(PROJECT, MODEL_NAME, MODEL_VERSION)
headers = {'Authorization': 'Bearer ' + token}
data = {
'instances': [
{
'X1':600,
'X2':8965,
'X3':17.93,
'X4':23,
'X5':52216.32776,
'X6':144.2442343,
'X7':0,
'X8':0,
'X9':0,
'X10':0
},
{
'X1':600,
'X2':6965,
'X3':17.93,
'X4':23,
'X5':52216.32776,
'X6':144.2442343,
'X7':0,
'X8':0,
'X9':0,
'X10':0
},
]
}
response = requests.post(api, json=data,headers=headers)
print(response)
print(response.content)
每次运行代码时,都会出现此错误。
Request had invalid authentication credentials. Expected OAuth 2 access token, login cookie or other valid authentication credential.
我正在Windows上使用python 3.8.3。
任何人都可以告诉我代码在哪里损坏或应该使用哪种身份验证方法。
答案 0 :(得分:0)
注意::OAUTH2CLIENT已过时,您需要改用GOOGLE-AUTH。
请在下面找到使用最新的Google OAuth库修改的代码:
import requests
import json
import google.auth
import google.auth.transport.requests
PROJECT = 'project-name'
MODEL_NAME = 'modelname'
MODEL_VERSION = 'version'
credentials, project_id = google.auth.default(
scopes=['https://www.googleapis.com/auth/cloud-platform','https://www.googleapis.com/auth/cloud-platform.read-only'])
api = 'https://ml.googleapis.com/v1/projects/{}/models/{}/versions/{}:predict' \
.format(PROJECT, MODEL_NAME, MODEL_VERSION)
request = google.auth.transport.requests.Request()
credentials.refresh(request)
token = credentials.token
headers = {'Authorization': 'Bearer ' + token}
data = {
"instances" : [
{
'X1':600,...
}
}
response = requests.post(api, json=data, headers=headers)
print(response)
print(response.content)
除了使用get_application_default()
之外,您还需要使用google.auth.default
,并且取决于所调用的API,必须定义适当的scopes才能访问Google API。
我在Google Cloud Shell中运行了相同的代码,并且运行良好。原因是:Google Cloud Shell在Compute Engine VM上运行,该VM已为登录帐户创建了OAuth令牌,并已保存在本地Compute Engine VM metadata server中。
如google.auth.default
documentation中所述,它检测到它正在Compute Engine VM中运行,并自动使用位于VM Metadata Server中的默认OAuth令牌。
从本地计算机运行代码时,需要使用以下身份验证方法之一,使自己的OAuth令牌可被代码访问:
-使用Service account:
google.auth.default
documentation代码还会检查此特殊环境变量以获取设置的JSON OAuth令牌,并自动使用它。- OR ,使用User account:
这可以通过运行following command生成令牌来实现:
gcloud auth application-default login
然后删除google.auth.default
代码,并将其替换为following command的输出:
gcloud auth application-default print-access-token