Python 中的 AWS Lambda 函数,生成字符串流

问题描述 投票:0回答:1

所以我想利用这个 .net 代码,在其中接收卡盘中的响应并分别处理每个块

    public async Task<string> InvokeLambdaFunctionAsync(string functionName, string payload)
    {
        var response = await _lambdaClient.InvokeAsync(new Amazon.Lambda.Model.InvokeRequest()
        {
            FunctionName = functionName,
            InvocationType = InvocationType.RequestResponse,
            Payload = payload
        });

        using (var responseStream = response.Payload)
        {
            using (var reader = new StreamReader(responseStream))
            {
                var result = "";
                var buffer = new char[4096];
                int bytesRead;

                while ((bytesRead = await reader.ReadAsync(buffer, 0, buffer.Length)) > 0)
                {
                    var chunk = new string(buffer, 0, bytesRead);
                    result += chunk;
                }

                return result;
            }
        }
    }

我使用的 lambda 函数是

import time

def lambda_handler(event, context):

  def generate_text():
    text_data = ["Line 1", "Line 2", "Line 3"]
    
    for line in text_data:
      yield line + "\n"
      time.sleep(1)

  if 'last_line_index' not in event:
    event['last_line_index'] = 0
    event['lines'] = list(generate_text())

  last_line_index = event['last_line_index']  
  lines = event['lines']

  if last_line_index < len(lines):
    response = {
      "statusCode": 200,
      "body": lines[last_line_index]
    }
    event['last_line_index'] += 1
  else:
    response = {"statusCode": 200, "body": ""}

  return response

但是我收到的回复是

回应 { “状态代码”:200, “正文”:“第 1 行” }

我没有收到第 2 行和第 3 行

是我需要可行的,如果是的话需要更新什么

python c# aws-lambda
1个回答
0
投票

这段代码中发生了几件事。

  1. 您没有迭代生成器的列表。该代码仅采用单个值。在您的情况下,
    lines
    列表的第一个元素
  2. 如果这样做,您将在每次迭代时覆盖响应正文。
  3. 您没有增加正确的变量。该代码正在更新
    event
    字典中的值,但您没有使用此变量来控制流程。

这将解决您的问题:

body = ""
if last_line_index < len(lines):
    while last_line_index < len(lines):
         body += lines[last_line_index]
         last_line_index += 1

    response = {"statusCode": 200, "body": body}
else:
    response = {"statusCode": 200, "body": body}
© www.soinside.com 2019 - 2024. All rights reserved.