首页 \ 问答 \ 通过Python实现Google Cloud Machine Learning Engine的在线预测(Implement online predictions of Google Cloud Machine Learning Engine by Python)

通过Python实现Google Cloud Machine Learning Engine的在线预测(Implement online predictions of Google Cloud Machine Learning Engine by Python)

我想将App Engine的请求发送到ML Engine的模型。

我构建了用于在本地计算机上进行测试的示例代码。 但是,我收到错误'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"
  }
}

我的示例代码:

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)

I want to send requests from App Engine to the model of ML Engine.

I built the sample code for testing on my local machine. However, I received the error '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)

原文:https://stackoverflow.com/questions/49758982
更新时间:2022-11-11 13:11

最满意答案

请验证LogErrorImport表上的主键。 确保它是一个设置为自动增量的标识列。 不要在代码中的任何位置设置此主键。 如果这些检查没有问题,则不应该出现重复的主键错误。

更新:您需要在trycatch块中使用using语句定义不同的'db'上下try ,以便它们不会相互冲突。 你可以这样做:

try
{
   using (var _context = new DBContext())
   {
      //Normal save logic here
     _context.Save();
   }
}
catch(Exception ex)
{
   using (var _context = new DBContext())
   {
      //Log error here
     _context.Save();
   }
}

Please verify the Primary Key on your LogErrorImport table. Make sure it is an identity column which is set to auto increment. Do not set this primary key anywhere in your code. If these checks are alright, you shouldn't be getting duplicate Primary Key error.

Update: You will need to define different sets of 'db' context in try and catch block with using statement so that they do not conflict with each other. You might do something like:

try
{
   using (var _context = new DBContext())
   {
      //Normal save logic here
     _context.Save();
   }
}
catch(Exception ex)
{
   using (var _context = new DBContext())
   {
      //Log error here
     _context.Save();
   }
}

相关问答

更多
  • 在这种情况下,您需要通过代码手动“退出”事务(通过异常或简单地检查错误状态),您不应该使用DB::transaction() ,而是将代码包装在DB::beginTransaction和DB::commit / DB::rollback() : DB::beginTransaction(); try { DB::insert(...); DB::insert(...); DB::insert(...); DB::commit(); // all good } ca ...
  • 得到它了! 忘记“在此方法中选择术语: private String SEL_ROW = "id," + "nameuser," + "kategorie," + "uebung," + "gewicht," + "datum " + "from " + DB_Table; Got it! Forgot "select term in this method: private String SEL_ROW = "id," + ...
  • Document d = null; 而不仅仅是 Document d; 尽管如此,当你使用d时,你不得不担心NullPointerException Document d = null; instead of just Document d; Though then you have to worry about NullPointerException later down the road when you use d
  • 编译器只是告诉您此时不需要捕获该异常。 SQLException是一个经过检查的异常,这意味着如果您明确地抛出它,或者您调用一个在其throws子句中声明它的方法,您的代码应该只能看到它。 这些特定的try / catch块中的代码都不适用。 你应该能够摆脱内部的try / catch块,也可能是外层的。 IIRC,理论上可以看到尚未声明的已检查异常,但除非您采取特殊措施才能实现,否则不太可能出现这种情况。 The compiler is simply telling you that you don't ...
  • 在您的查询中,您使用:dt作为占位符,但在类构造函数中使用$this->birth_date 。 一旦转换,这将创建一个索引为' birth_date'的数组,该数组与命名参数"dt"不匹配:选择一个或另一个。 In your query you use :dt as a placeholder, but in the class constructor you use $this->birth_date. Once casted, this will create an array with index ...
  • 如果IF语句的计算结果为false,PRINT @@ ERROR行是否会执行? 简单回答NO 。 你可以尝试自己看看。 只有当IF ..块的计算结果为TRUE时才会出现。 请参阅下面的示例代码 alter procedure testsp as begin declare @var int; IF EXISTS ( SELECT Name FROM student WHERE Marks < 90 ) BEGIN TRY set @var = 20/0; END TRY BEGIN CATC ...
  • 如果您需要记录并邮寄每个异常,那么您需要这样的东西: class RefundServiceInvoker { private $_orders; public function refundOrder() { try { $this->getOrdersFromDB(); foreach ($this->_orders as $order) { try { $order->refund() ...
  • private void SetupConnection() { conn.ConnectionString = ConfigurationManager.ConnectionStrings["ZenLive"].ConnectionString; bool success = false; while(!success) { try { OdbcDataAdapter da = ...
  • 请验证LogErrorImport表上的主键。 确保它是一个设置为自动增量的标识列。 不要在代码中的任何位置设置此主键。 如果这些检查没有问题,则不应该出现重复的主键错误。 更新:您需要在try和catch块中使用using语句定义不同的'db'上下try ,以便它们不会相互冲突。 你可以这样做: try { using (var _context = new DBContext()) { //Normal save logic here _context.Save(); ...
  • 鉴于你评论中的额外信息,我会说你只是想要这个 $seleccion = is_array($_POST['seleccion']) ? implode(', ', $_POST['seleccion']) : $_POST['seleccion']; // snip $statement->execute(array( $_POST['gestas'], $_POST['abortos'], $_POST['esp_conse'], $seleccion, ...

相关文章

更多

最新问答

更多
  • 散列包括方法和/或嵌套属性(Hash include methods and/or nested attributes)
  • TensorFlow:基于索引列表创建新张量(TensorFlow: Create a new tensor based on list of indices)
  • 企业安全培训的各项内容
  • 错误:RPC失败;(error: RPC failed; curl transfer closed with outstanding read data remaining)
  • NumPy:将int64值存储在np.array中并使用dtype float64并将其转换回整数是否安全?(NumPy: Is it safe to store an int64 value in an np.array with dtype float64 and later convert it back to integer?)
  • 注销后如何隐藏导航portlet?(How to hide navigation portlet after logout?)
  • 将多个行和可变行移动到列(moving multiple and variable rows to columns)
  • 对setOnInfoWindowClickListener的意图(Intent on setOnInfoWindowClickListener)
  • Angular $资源不会改变方法(Angular $resource doesn't change method)
  • 如何配置Composite C1以将.m和桌面作为同一站点提供服务(How to configure Composite C1 to serve .m and desktop as the same site)
  • 不适用:悬停在悬停时:在元素之前[复制](Don't apply :hover when hovering on :before element [duplicate])
  • Mysql DB单个字段匹配多个其他字段(Mysql DB single field matching to multiple other fields)
  • 产品页面上的Magento Up出售对齐问题(Magento Up sell alignment issue on the products page)
  • 是否可以嵌套hazelcast IMaps?(Is it possible to nest hazelcast IMaps? And whick side effects can I expect? Is it a good Idea anyway?)
  • UIViewAnimationOptionRepeat在两个动画之间暂停(UIViewAnimationOptionRepeat pausing in between two animations)
  • 在x-kendo-template中使用Razor查询(Using Razor query within x-kendo-template)
  • 在BeautifulSoup中替换文本而不转义(Replace text without escaping in BeautifulSoup)
  • 如何在存根或模拟不存在的方法时配置Rspec以引发错误?(How can I configure Rspec to raise error when stubbing or mocking non-existing methods?)
  • asp用javascript(asp with javascript)
  • “%()s”在sql查询中的含义是什么?(What does “%()s” means in sql query?)
  • 如何为其编辑的内容提供自定义UITableViewCell上下文?(How to give a custom UITableViewCell context of what it is editing?)
  • c ++十进制到二进制,然后使用操作,然后回到十进制(c++ Decimal to binary, then use operation, then back to decimal)
  • 以编程方式创建视频?(Create videos programmatically?)
  • 无法在BeautifulSoup中正确解析数据(Unable to parse data correctly in BeautifulSoup)
  • webform和mvc的区别 知乎
  • 如何使用wadl2java生成REST服务模板,其中POST / PUT方法具有参数?(How do you generate REST service template with wadl2java where POST/PUT methods have parameters?)
  • 我无法理解我的travis构建有什么问题(I am having trouble understanding what is wrong with my travis build)
  • iOS9 Scope Bar出现在Search Bar后面或旁边(iOS9 Scope Bar appears either behind or beside Search Bar)
  • 为什么开机慢上面还显示;Inetrnet,Explorer
  • 有关调用远程WCF服务的超时问题(Timeout Question about Invoking a Remote WCF Service)