gpt4 book ai didi

python - Kinesis Firehose λ 转换

转载 作者:太空狗 更新时间:2023-10-30 02:37:22 25 4
gpt4 key购买 nike

我有以下 lambda 函数作为 Kinesis firehose 记录转换的一部分,它将 msgpack 记录从 kinesis 输入流转换为 json。

Lambda 运行时:python 3.6

from __future__ import print_function

import base64
import msgpack
import json
print('Loading function')


def lambda_handler(event, context):
output = []

for record in event['records']:
payload = msgpack.unpackb(base64.b64decode(record['data']), raw=False)

# Do custom processing on the payload here
output_record = {
'recordId': record['recordId'],
'result': 'Ok',
'data': json.dumps(payload, ensure_ascii=False).encode('utf8')
}
output.append(output_record)

print('Successfully processed {} records.'.format(len(event['records'])))
return {'records': output}

但是 lambda 抛出以下错误:

An error occurred during JSON serialization of response: b'
{
"id": "d23fd47f-3a62-4383-bcb3-abdb913ea572",
"timestamp": 1526358140730,
"message": "Hello World"
}
' is not JSON serializable
Traceback (most recent call last):
File "/var/lang/lib/python3.6/json/__init__.py", line 238, in dumps
**kw).encode(obj)
File "/var/lang/lib/python3.6/json/encoder.py", line 199, in encode
chunks = self.iterencode(o, _one_shot=True)
File "/var/lang/lib/python3.6/json/encoder.py", line 257, in iterencode
return _iterencode(o, 0)
File "/var/runtime/awslambda/bootstrap.py", line 110, in
decimal_serializer
raise TypeError(repr(o) + " is not JSON serializable")

我做错了什么吗?

最佳答案

我能够解决这个问题。

这是对我有用的代码。

from __future__ import print_function

import base64
import msgpack
import json

print('Loading function')


def lambda_handler(event, context):
output = []

for record in event['records']:
payload = msgpack.unpackb(base64.b64decode(record['data']), raw=False)

# Do custom processing on the payload here
output_record = {
'recordId': record['recordId'],
'result': 'Ok',
'data': base64.b64encode(json.dumps(payload).encode('utf-8') + b'\n').decode('utf-8')
}
output.append(output_record)

print('Successfully processed {} records.'.format(len(event['records'])))
return {'records': output}

关于python - Kinesis Firehose λ 转换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50352545/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com