【问题标题】:How to return byte array from AWS Lambda API gateway?如何从 AWS Lambda API 网关返回字节数组?
【发布时间】:2020-07-16 13:13:30
【问题描述】:

我是一个初学者,所以我希望在这里得到一些帮助。

我想创建一个 lambda 函数(用 Python 编写),它能够读取存储在 S3 中的图像,然后将图像作为二进制文件(例如字节数组)返回。 lambda 函数由 API 网关触发。

现在,我已经设置了 API 网关来触发 Lambda 函数,它可以返回一个 hello 消息。我还有一个存储在 S3 存储桶中的 gif 图像。

import base64
import json
import boto3

s3 = boto.client('s3')

def lambda_handler(event, context):
# TODO implement
bucket = 'mybucket'
key = 'myimage.gif'

s3.get_object(Bucket=bucket, Key=key)['Body'].read()
return {
    "statusCode": 200,
    "body": json.dumps('Hello from AWS Lambda!!')
}

我真的不知道如何继续。任何人都可以建议吗?提前致谢!

【问题讨论】:

  • AWS Lambda 有 6mb 响应正文限制,同样在 lambda 中,您按 100 毫秒计费,所以我认为更好的解决方案是返回直接 s3 下载链接,但如果您仍想从 lambda 返回二进制数据,检查这个问题stackoverflow.com/questions/44860486/…

标签: python amazon-web-services amazon-s3 aws-lambda


【解决方案1】:

您可以从您的 Lambda 函数返回带有适当标头的 Base64 编码数据。

这里是更新的 Lambda 函数:

import base64
import boto3

s3 = boto3.client('s3')


def lambda_handler(event, context):
    bucket = 'mybucket'
    key = 'myimage.gif'

    image_bytes = s3.get_object(Bucket=bucket, Key=key)['Body'].read()

    # We will now convert this image to Base64 string
    image_base64 = base64.b64encode(image_bytes)

    return {'statusCode': 200,
            # Providing API Gateway the headers for the response
            'headers': {'Content-Type': 'image/gif'},
            # The image in a Base64 encoded string
            'body': image_base64,
            'isBase64Encoded': True}

更多细节和分步指南,可以参考这个官方blog

【讨论】:

  • @Khan,如果答案确实解决了您的问题,您介意接受吗。这样,其他偶然发现此问题的人可以轻松找到解决方案。干杯。
猜你喜欢
  • 2021-12-13
  • 2018-10-05
  • 1970-01-01
  • 1970-01-01
  • 2017-11-24
  • 2017-11-13
  • 2017-04-27
  • 2019-05-02
  • 1970-01-01
相关资源
最近更新 更多