我正在尝试使用aws chalice、一个lambda函数和一个API Gateaway调用我的sagemaker模型。
我正在尝试通过POST请求发送图像,但在lambda函数上接收它时遇到问题。
我的代码看起来像这样:
from chalice import Chalice
from chalice import BadRequestError
import base64
import os
import boto3
import ast
import json
app = Chalice(app_name='foo')
app.debug = True
@app.route('/', methods=['POST'], content_types=['application/json'])
def index():
body = ''
try:
body = app.current_request.json_body # <- I suspect this is the problem
return {'response': body}
except Exception as e:
return {'error': str(e)}它只是回来了
<Response [200]> {'error': 'BadRequestError: Error Parsing JSON'}
正如我之前提到的,我的最终目标是接收我的图像,并用它发出一个sagemaker请求。但我就是看不懂这张图片。
我的python测试客户端如下所示:
import base64, requests, json
def test():
url = 'api_url_from_chalice'
body = ''
with open('b1.jpg', 'rb') as image:
f = image.read()
body = base64.b64encode(f)
payload = {'data': body}
headers = {'Content-Type': 'application/json'}
r = requests.post(url, data=payload, headers=headers)
print(r)
r = r.json()
# r = r['response']
print(r)
test()请帮帮我,我花了很多时间试图弄清楚这件事
发布于 2020-04-03 07:26:08
因此,我能够在aws工程师的帮助下解决这个问题(我想我很幸运)。我包含了完整的lambda函数。客户端上没有任何更改。
from chalice import Chalice
from chalice import BadRequestError
import base64
import os
import boto3
import ast
import json
import sys
from chalice import Chalice
if sys.version_info[0] == 3:
# Python 3 imports.
from urllib.parse import urlparse, parse_qs
else:
# Python 2 imports.
from urlparse import urlparse, parse_qs
app = Chalice(app_name='app_name')
app.debug = True
@app.route('/', methods=['POST'])
def index():
parsed = parse_qs(app.current_request.raw_body.decode())
body = parsed['data'][0]
print(type(body))
try:
body = base64.b64decode(body)
body = bytearray(body)
except e:
return {'error': str(e)}
endpoint = "object-detection-endpoint_name"
runtime = boto3.Session().client(service_name='sagemaker-runtime', region_name='us-east-2')
response = runtime.invoke_endpoint(EndpointName=endpoint, ContentType='image/jpeg', Body=body)
print(response)
results = response['Body'].read().decode("utf-8")
results = results['predictions']
results = json.loads(results)
results = results['predictions']
return {'result': results}发布于 2020-03-31 00:51:38
该错误消息是因为您没有将JSON body发送到Chalice应用程序。检查这一点的一种方法是使用.raw_body属性进行确认:
@app.route('/', methods=['POST'], content_types=['application/json'])
def index():
body = ''
try:
#body = app.current_request.json_body # <- I suspect this is the problem
return {'response': app.current_request.raw_body.decode()}
except Exception as e:
return {'error': str(e)}您将看到主体是表单编码的,而不是JSON。
$ python client.py
<Response [200]>
{'response': 'data=c2FkZmFzZGZhc2RmYQo%3D'}要解决此问题,可以在requests.post()调用中使用json参数:
r = requests.post(url, json=payload, headers=headers)然后我们可以确认我们在你的圣杯应用中得到了一个JSON body:
$ python client.py
<Response [200]>
{'response': '{"data": "c2FkZmFzZGZhc2RmYQo="}'}https://stackoverflow.com/questions/60903256
复制相似问题