我正在使用 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/