简体   繁体   English

如何通过 AWS Lambda(python) 返回 io.BufferedReader?

[英]How to return io.BufferedReader through AWS Lambda(python)?

I am trying to read a file from the S3 bucket, get the file in an io.BufferedReader and return it in via lambda function that would later decode to JSON.我正在尝试从 S3 存储桶读取文件,将文件放入 io.BufferedReader 并通过 lambda 函数将其返回,该函数稍后将解码为 JSON。 I am getting an error message as我收到一条错误消息

Unable to marshal response: Object of type BufferedReader is not JSON serializable无法封送响应:BufferedReader 类型的对象不是 JSON 可序列化的

My code is mentioned below.我的代码在下面提到。

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":f,
        "content":f.read()
    }

Error Response from lambda来自 lambda 的错误响应

Response
{
  "errorMessage": "Unable to marshal response: Object of type BufferedReader is not JSON serializable",
  "errorType": "Runtime.MarshalError",
  "requestId": "10aea120-fafc-4080-a598-79a89182da64",
  "stackTrace": []
}

I am using the AWS-Lambda Python function我正在使用 AWS-Lambda Python 函数

f.read() return bytes and JSON does not support binary data. f.read()返回字节,JSON 不支持二进制数据。 Also "file":f is incorrect.同样"file":f不正确。 Guess it should be a filename.猜猜它应该是一个文件名。 Anyway, usually you would return binary data in JSON as base64 :无论如何,通常你会在 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())
    }

Then on the client side, you have to decode base64 to binary.然后在客户端,您必须将base64解码为二进制。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM