通过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
最满意答案
请验证
LogErrorImport
表上的主键。 确保它是一个设置为自动增量的标识列。 不要在代码中的任何位置设置此主键。 如果这些检查没有问题,则不应该出现重复的主键错误。更新:您需要在
try
和catch
块中使用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
andcatch
block withusing
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(); } }
相关问答
更多-
Laravel:使用try ... catch与DB :: transaction()(Laravel: Using try…catch with DB::transaction())[2022-07-07]
在这种情况下,您需要通过代码手动“退出”事务(通过异常或简单地检查错误状态),您不应该使用DB::transaction() ,而是将代码包装在DB::beginTransaction和DB::commit / DB::rollback() : DB::beginTransaction(); try { DB::insert(...); DB::insert(...); DB::insert(...); DB::commit(); // all good } ca ... -
保存对象在Insert语句中导致NullPointerException(Saving object caused NullPointerException in Insert statement)[2022-12-08]
得到它了! 忘记“在此方法中选择术语: 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 ...
-
SQLSTATE [HY093]:插入mysql db期间的pdo语句(SQLSTATE[HY093] : pdo statement during insert into mysql db)[2022-06-29]
在您的查询中,您使用: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() ...
-
帮助try catch语句(help with try catch statement)[2024-03-28]
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, ...