简体   繁体   English

通过Python实现Google Cloud Machine Learning Engine的在线预测

[英]Implement online predictions of Google Cloud Machine Learning Engine by Python

I want to send requests from App Engine to the model of ML Engine. 我想将App Engine的请求发送到ML Engine的模型。

I built the sample code for testing on my local machine. 我构建了用于在本地计算机上进行测试的示例代码。 However, I received the error 'UNAUTHENTICATED': 但是,我收到错误'UNAUTHENTICATED':

WARNING:root:No ssl package found. urlfetch will not be able to validate SSL certificates.
91bnQuY34Oh8cJyF=....
{
  "error": {
    "code": 401,
    "message": "Request had invalid authentication credentials. Expected OAuth 2 access token, login cookie or other valid authentication credential. See https://developers.google.com/identity/sign-in/web/devconsole-project.",
    "status": "UNAUTHENTICATED"
  }
}

My sample code: 我的示例代码:

from google.appengine.api import urlfetch
import urllib
import time
import jwt

data_to_post = {"instances":[{"text":[185,15,14,124,370,832,112,120,...]}]}
encoded_data = urllib.urlencode(data_to_post)

model_url = 'https://ml.googleapis.com/v1/projects/myproject/models/analyizesentiment:predict'

from google.appengine.api import apiproxy_stub_map 
from google.appengine.api import urlfetch_stub
apiproxy_stub_map.apiproxy = apiproxy_stub_map.APIProxyStubMap() 
apiproxy_stub_map.apiproxy.RegisterStub('urlfetch', urlfetch_stub.URLFetchServiceStub())

PRIVATE_KEY_ID_FROM_JSON = '??????????????????'
PRIVATE_KEY_FROM_JSON = "-----BEGIN PRIVATE KEY-----\n??????????\n-----END PRIVATE KEY-----\n"
iat = time.time()
exp = iat + 3600
payload = {'iss': 'accountname@myprojectname.iam.gserviceaccount.com',
           'sub': 'accountname@myprojectname.iam.gserviceaccount.com',
           'aud': 'https://ml.googleapis.com/v1/',
           'iat': iat,
           'exp': exp}
additional_headers = {'kid': PRIVATE_KEY_ID_FROM_JSON,
                      'alg': "RS256",
                      "typ": "JWT",}
signed_jwt = jwt.encode(payload, PRIVATE_KEY_FROM_JSON, headers=additional_headers, algorithm='RS256')
print(signed_jwt)

result = urlfetch.fetch(model_url, encoded_data, method=urlfetch.POST, headers={'Content-type': 'application/json', 'Authorization': 'Bearer ' + signed_jwt})
print(result.content)

What is lacking is a header with 缺少的是标题

headername: "Authorization" value: "Bearer $token" headername:“授权”价值:“Bearer $ token”

where token is a oauth token. 其中token是一个oauth令牌。 You can generate token using 您可以使用生成令牌

gcloud auth login

Or you can download the token for a service account. 或者,您可以下载服务帐户的令牌。 A useful read: https://developers.google.com/api-client-library/python/guide/aaa_oauth 一个有用的阅读: https//developers.google.com/api-client-library/python/guide/aaa_oauth

However, on a appengine, you should be able to get it from standard credentials apis 但是,在appengine上,您应该能够从标准凭证apis获取它

You can also modify your example to use a Credentials object and programmatically append that header. 您还可以修改示例以使用Credentials对象,并以编程方式附加该标头。

from googleapiclient import discovery
from oauth2client.client import GoogleCredentials

PROJECT=''
MODEL=''
VERSION=''
credentials = GoogleCredentials.get_application_default()
api = discovery.build('ml', 'v1', credentials=credentials)

# Add your sample instances here.
request_data = {'instances':[] }

parent = 'projects/%s/models/%s/versions/%s' % (PROJECT, MODEL, VERSION)
response = api.projects().predict(body=request_data, name=parent).execute()
print "response={0}".format(response)

The execute() method above can take http object if you wanted to provide a different timeouts. 如果要提供不同的超时,上面的execute()方法可以使用http对象。 And you should be able to provide the additional headers. 而且你应该能够提供额外的标题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM