为什么AWS Lambda Internel服务器错误500但在Endpoint SageMaker中成功/调用POST


import os
import io
import boto3
import json
import csv

# grab environment variables
ENDPOINT_NAME = os.environ['ENDPOINT_NAME']
# grab runtime client
runtime = boto3.client('runtime.sagemaker')
def lambda_handler(event, context):
# Load data from POST request
data = json.loads(json.dumps(event))

# Grab the payload
payload = data['body']

# Invoke the model. In this case the data type is a JSON but can be other things such as a CSV
response = runtime.invoke_endpoint(EndpointName=ENDPOINT_NAME,
ContentType='application/json',
Body=payload)

# Get the body of the response from the model
result = response['Body'].read().decode()
# Return it along with the status code of 200 meaning this was succesful 
return {
'statusCode': 200,
'body': result
}

AWS Lambda的响应

{
"errorMessage": "'body'",
"errorType": "KeyError",
"stackTrace": [
[
"/var/task/lambda_function.py",
18,
"lambda_handler",
"payload = data['body']"
]
]
}

Postman 500内部服务器错误的响应

但在SageMaker Endpoint 中成功调用POST 200

问题是当您试图用数据['body']解析负载时。数据的传递格式不是终结点所期望的格式。使用以下代码片段正确格式化/序列化端点的数据。为了让这一切变得更清楚,请确保检查您的有效负载类型,以确保您没有意外地再次序列化。

data = json.loads(json.dumps(event))
payload = json.dumps(data)
response = runtime.invoke_endpoint(EndpointName=ENDPOINT_NAME,
ContentType='application/json',
Body=payload)
result = json.loads(response['Body'].read().decode())

我在AWS&我的观点是我自己的

最新更新