python-3.x - AWS Lambda Python - 返回 BytesIO 文件?

标签 python-3.x amazon-web-services aws-lambda serverless-framework

我正在使用 python 3.7 在 AWS Lambda 中设置一个函数,它不会让我返回字节类型

请注意这是 API 网关不是问题 ,我直接调用了 lambda。

错误是:Runtime.MarshalError, ... is not JSON serializable

output = BytesIO()
#Code that puts an excel file into output...
return {
        'Content-Disposition': 'attachment; filename="export.xlsx"',
        'Content-Type': 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
        'body' : output.getvalue()
    }

如果我做 :
'body' : str(output.getvalue())

它输出一个损坏的文件,因为它添加了 b''到字符串

如果我做 :
'body' : base64.b64encode(output.getvalue()).decode()

它还输出损坏的文件,可能是因为它更改了文件的二进制表示。

也许我需要上传到 S3?但它不适合我的流程,这是一次性文件创建,它会一直停留在“S3 Limbo”中,直到 TTL

最佳答案

无法从直接调用的 AWS Lambda 函数返回未编码的二进制数据。
docs :

If the handler returns objects that can't be serialized by json.dumps, the runtime returns an error.


您可以使用 API Gateway 执行此操作的原因是 API Gateway 正在执行将您的函数返回的 base64 JSON 内容转换为二进制文件的过程。 (参见文档 here)
我需要更多地了解您如何调用 Lambda 才能确定,但​​我怀疑您可以将相同的 base64 解码逻辑实现到您的直接调用客户端中。或者,如果您想让客户端尽可能简单,请将 S3 与生命周期 Hook 一起使用,以防止存储桶被临时文件填满。

关于python-3.x - AWS Lambda Python - 返回 BytesIO 文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57183102/

相关文章:

python - 如何在 Python (cuPy/Numpy) 中将行与相应的列相乘?

python - 值错误 : Input 0 of node incompatible with expected float_ref. **

python - 在 setup.py (distutils.extension) 中更改输出文件名

node.js - 如何将使用 Sharp 库的无服务器框架应用程序部署到 AWS?

amazon-web-services - 无法看到 CloudFormation cloudwatch 命名空间

node.js - AWS Lambda setupRequestListerners RequestEntityTooLargeException claudia.js

Python argparse 示例?

amazon-web-services - Dynamodb 缺少并发请求的更新?

aws-lambda - AWS Lambda/SAM : How to get invocation URI from CLI?

amazon-web-services - 如何在AWS Step Functions中指定多个结果路径值