【问题标题】:How to return io.BufferedReader through AWS Lambda(python)?如何通过 AWS Lambda(python) 返回 io.BufferedReader?
【发布时间】:2021-10-19 20:50:15
【问题描述】:

我正在尝试从 S3 存储桶中读取文件,在 io.BufferedReader 中获取文件并通过 lambda 函数将其返回,该函数稍后将解码为 JSON。 我收到一条错误消息

无法编组响应:BufferedReader 类型的对象不是 JSON 可序列化的

下面提到了我的代码。

s3 = boto3.client('s3')
def lambda_handler(event, context):
    bucket = "bucketID"
    body = []
    for record in event['key']:
        with open('/tmp/2021-10-11T06:23:29:691472.pdf', 'wb') as f:
            s3.download_fileobj(bucket, "basedir/file.pdf", f)
        f = open("/tmp/2021-10-11T06:23:29:691472.pdf", "rb")
    body.append(f)
    
    return {
        "statusCode": 200,
        "file":f,
        "content":f.read()
    }

来自 lambda 的错误响应

Response
{
  "errorMessage": "Unable to marshal response: Object of type BufferedReader is not JSON serializable",
  "errorType": "Runtime.MarshalError",
  "requestId": "10aea120-kyc-jpk-bnce-7123eTyda64",
  "stackTrace": []
}

我正在使用 AWS-Lambda Python 函数

【问题讨论】:

  • 你试过f.read().dumps()吗?

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


【解决方案1】:

f.read() 返回字节并且 JSON 不支持二进制数据。 "file":f 也不正确。猜猜它应该是一个文件名。无论如何,通常您会将 JSON 格式的二进制数据返回为base64

import base64

s3 = boto3.client('s3')
def lambda_handler(event, context):
    bucket = "document.as.a.service.test"
    body = []
    for record in event['uuid_filepath']:
        with open('/tmp/2021-10-11T06:23:29:691472.pdf', 'wb') as f:
            s3.download_fileobj(bucket, "123TfZ/2021-10-11T06:23:29:691472.pdf", f)
        f = open("/tmp/2021-10-11T06:23:29:691472.pdf", "rb")
    body.append(f)
    
    return {
        "statusCode": 200,
        "file": "2021-10-11T06:23:29:691472.pdf",
        "content": base64.b64encode(f.read())
    }

然后在客户端,您必须将base64 解码为二进制。

【讨论】:

    猜你喜欢
    • 2021-10-23
    • 1970-01-01
    • 2021-07-29
    • 2017-04-19
    • 1970-01-01
    • 1970-01-01
    • 2022-01-24
    • 1970-01-01
    • 2020-04-24
    相关资源
    最近更新 更多