json 为什么我从AWS lambda函数得到空白响应,即使AWS lambda测试正常工作?

xzabzqsa  于 2023-10-21  发布在  其他
关注(0)|答案(2)|浏览(102)

bounty还有6天到期。此问题的答案有资格获得+50声望奖励。Danish Xavier正在寻找一个答案从一个有信誉的来源:如果有一个代码问题,请给予我的固定代码太。

说明

我正在使用AWS lambda函数在我的前端和后端之间创建一个中间服务。该函数的工作是从UI获取有效负载并发送到后端,如果后端是活动的,则发送200状态(ML模型的进度,短池)。假设后端不是live,后端pod正在重新启动,使用保存在response.json文件中的先前JSON,并将其返回到前端,直到pod重新启动并提供服务。这是我的lambda函数。
我的AWS Lambda代码

import json
import os
import requests

def save_json_file_to_tmp(response_payload, filename="response.json"):
    tmp_dir = "/tmp"
    tmp_file_path = os.path.join(tmp_dir, filename)
    with open(tmp_file_path, "w") as f:
        json.dump(response_payload, f)

def read_json_file(filename="response.json"):
    tmp_dir = "/tmp"
    tmp_file_path = os.path.join(tmp_dir, filename)
    with open(filename, "r") as f:
        # Load the JSON payload.
        response_payload = json.load(f)

    return response_payload

def lambda_handler(event, context):
    """Forwards a POST request to another service and redirects back to the first microservice.

    Args:
        event: The Lambda event.
        context: The Lambda context.

    Returns:
        A JSON response object.
    """
    
    print(event)
    print(type(event))
    print("=========================================================")

    # Get the request data from the event.
    
    try:
        request_data = json.loads(event["body"])
    except KeyError as e:
        request_data = event

    # Get the destination URL from the request data.
    dest_url = request_data["dest_url"]

    # Forward the POST request to the destination service.
    response = requests.post(dest_url, json=request_data)

    # Check the response status code.
    if response.status_code == 200:
        # Get the response payload.
        response_payload = json.loads(response.content)
        print("++++++++++++++++++++++++++++++++++")
        print(response_payload)
        print("++++++++++++++++++++++++++++++++++")
        # Save the response payload to a temporary file.
        save_json_file_to_tmp(response_payload)

        # Redirect back to the first microservice with the response payload.
        return {
            "statusCode": 200,
            "body": json.dumps(response_payload),
            "headers": {
                "Content-Type": "application/json"
            }
        }
    elif response.status_code == 502:
        # Read the response payload from the temporary file.
        response_payload = read_json_file_to_tmp()

        # Redirect back to the first microservice with the response payload.
        return {
            "statusCode": 200,
            "body": json.dumps(response_payload),
            "headers": {
                "Content-Type": "application/json"
            }
        }
    else:
        # Return an error response.
        return {
            "statusCode": 500,
            "body": json.dumps({
                "error": "Unexpected response from destination service."
            }),
            "headers": {
                "Content-Type": "application/json"
            }
        }

现在,为了测试lambda,我创建了一个测试事件checkLiveOrNot

{
  "app": "my_app",
  "session_id": "3432428374827347234",
  "table": "progress",
  "user_id": "[email protected]",
  "flag": false,
  "project_name": "mybig1gbproject",
  "user_name": "john doe",
  "file_name": "",
  "fit_progress": 0,
  "model_fit": 0,
  "total_fit": 0,
  "model_calc": 0,
  "total_calc": 0,
  "calc_progress": 0,
  "model_arch": "lambda",
  "dest_url": "https://mybackendservice/api/maincore/progress"
}

并调用它,它在lambda测试控制台中返回了正确的输出。

Test Event Name
checkLiveOrNot

Response
{
  "statusCode": 200,
  "body": "{\"_id\": \"34347tyi738483h8d73h\", \"session_id\": \"3432428374827347234\", \"data\": 0, \"model_no\": 0, \"table\": \"progress\", \"total_fit\": 1, \"total_calc\": 1, \"orc_fail\": 0, \"model_progress\": 0.0, \"current_model\": 0, \"model_progress\": 100.0, \"current_calc\": 1}",
  "headers": {
    "Content-Type": "application/json"
  }
}

Function Logs
START RequestId: 0d820ce34rtry9-2e11-420dsdfa-961e-c4434515b18f Version: $LATEST
{'app': 'my-app', 'session_id': '34347tyi738483h8d73h', 'table': 'progress', 'user_id': '[email protected]', 's3_flag': False, 'project_name': 'checksampleforapitesting', 'user_name': 'danish.xavier', 'file_name': '', 'model_fit_progress': 0, 'current_model_fit': 0, 'total_model_fit': 0, 'current_model_calc': 0, 'total_model_calc': 0, 'model_calc_progress': 0, 'model_arch': 'eks', 'dest_url': 'https://promo-internal-promo-usv-demotemp-env.mmx.mco.solutions.iqvia.com/api/core/progress_lambda'}
<class 'dict'>
=========================================================
++++++++++++++++++++++++++++++++++
{'_id': '34347tyi738483h8d73h', 'session_id': '34347tyi738483h8d73h', 'data': 0, 'model_no': 0, 'table': 'progress', 'total_fit': 1, 'total_calc': 1, 'orc_fail': 0, 'model_progress': 0.0, 'current_model': 0, 'model_progress': 100.0, 'current_calc': 1}
++++++++++++++++++++++++++++++++++
END RequestId: 0d820ce9-2e11-420a-961e-c4434515b18f
REPORT RequestId: 0d82dfdf0ce9-2dfdfe11-42dfdf0a-961e-c44345dfdf15b18f  Duration: 281.79 ms Billed Duration: 282 ms Memory Size: 128 MB Max Memory Used: 54 MB  Init Duration: 324.60 ms

Request ID
0d820ce9-2e11-420a-961e-c4434515b18f

现在,当我通过postman向这个lambda发送一个POST请求时,我得到了200个响应,但在Postman屏幕上什么也没有显示。我试着用python写了一个请求。这是密码。

import json
import requests

# Create the request headers
headers = {
    'Content-Type': 'application/json'
}

# Create the request body
payload = {
  "app": "my_app",
  "session_id": "3432428374827347234",
  "table": "progress",
  "user_id": "[email protected]",
  "flag": false,
  "project_name": "mybig1gbproject",
  "user_name": "john doe",
  "file_name": "",
  "fit_progress": 0,
  "model_fit": 0,
  "total_fit": 0,
  "model_calc": 0,
  "total_calc": 0,
  "calc_progress": 0,
  "model_arch": "lambda",
  "dest_url": "https://mybackendservice/api/maincore/progress"
}

# Send the POST request
response = requests.post(
    'https://8973043wa7lrta.execute-api.us-east-1.amazonaws.com/dev/progress_lambda',
    headers=headers,
    json=payload
)

# Check the response status code
if response.status_code == 200:
    # The request was successful
    print('Request successful')

    # Get the response payload
    response_payload = response.content

    print(response_payload)

程序的输出:

Request successful
b''
iezvtpos

iezvtpos1#

有没有这种可能性:
当response.status_code == 502时,您的代码也返回statusCode == 200,但response_payload为空

7gcisfzg

7gcisfzg2#

如果我正确理解你的功能:使用目录 /tmp 来保存对外部服务(API或其他)的调用结果。稍后,当再次调用Lambda函数时,同时外部服务返回502而不是200,您希望Lambda函数重用之前保存的响应。
但这是不可能做到这一点使用临时目录 /tmp。这个目录可以在Lambda函数中使用,但仅用于保存在Lambda函数的同一执行中重复使用的内容。/tmp 不会在同一Lambda函数的多个示例之间共享。
解决方案可能是不使用 /tmp 进行写/读,而是使用外部服务来写/读响应,如S3或任何其他数据库或缓存系统。
查看AWS Lambda FAQ
如果您的应用程序需要持久的存储,请考虑使用Amazon S3或Amazon EFS。如果您的应用程序需要在单个函数调用中存储代码所需的数据,请考虑使用AWS Lambda临时存储作为临时缓存。
安还说:
保持函数无状态使AWS Lambda能够根据需要快速启动函数的尽可能多的副本,以扩展到传入事件的速率。虽然AWS Lambda的编程模型是无状态的,但您的代码可以通过调用其他Web服务(如Amazon S3或Amazon DynamoDB)来访问有状态数据。

相关问题