在 Zapier 中使用此代码时,为什么会出现 Runtime.MarshalError?

Sam*_*art 6 python zapier

以下代码给了我:

Runtime.MarshalError:无法编组响应:{'Yes'} 不是 JSON 可序列化的

from calendar import monthrange

def time_remaining_less_than_fourteen(year, month, day):
    a_year = int(input['year'])
    b_month = int(input['month'])
    c_day = int(input['day'])
    days_in_month = monthrange(int(a_year), int(b_month))[1]
    time_remaining = ""

    if (days_in_month - c_day) < 14:
        time_remaining = "No"
        return time_remaining

    else:
        time_remaining = "Yes"
        return time_remaining


output = {time_remaining_less_than_fourteen((input['year']), (input['month']), (input['day']))}

#print(output)
Run Code Online (Sandbox Code Playgroud)

当我删除 {...} 它然后抛出:'unicode' object has no attribute 'copy'

Mar*_*cin 23

我在使用kinesis-firehose-process-record-pythonKinesis Firehose 的lambda 转换蓝图时遇到了这个问题,这导致我来到这里。因此,我将向在 lambda 出现问题时也发现此问题的任何人发布解决方案。

蓝图是:

from __future__ import print_function

import base64

print('Loading function')


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

    for record in event['records']:
        print(record['recordId'])
        payload = base64.b64decode(record['data'])

        # Do custom processing on the payload here

        output_record = {
            'recordId': record['recordId'],
            'result': 'Ok',
            'data': base64.b64encode(payload)
        }
        output.append(output_record)

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

    return {'records': output}
Run Code Online (Sandbox Code Playgroud)

需要注意的是,AWS 提供的用于 Python 的 Firehose lambda 蓝图是针对 Python 2.7 的,它们不适用于 Python 3。原因是在 Python 3 中,字符串和字节数组是不同的。

使其与由 Python 3.x 运行时支持的 lambda 配合使用的关键更改是:

改变

'data': base64.b64encode(payload)
Run Code Online (Sandbox Code Playgroud)

进入

'data': base64.b64encode(payload).decode("utf-8")
Run Code Online (Sandbox Code Playgroud)

否则,由于无法使用从base64.b64encode.

  • 谢谢Marcin,我也遇到了同样的问题,你的回答让我省了很多麻烦。Python 2.7 蓝图让我相信 Kinesis 期望“字节”作为记录的数据。我什至没有想到转换为“str”。快速建议:`base64.b64encode(payload).decode("utf-8")`可以简单地是`base64.b64encode(payload).decode()`。根据定义,Base64 数据是 ASCII。ASCII 本身是 UTF-8,这是 Python 3 中编码参数的默认值。指定编解码器只是多余的。 (2认同)
  • @Rafa 很高兴我的回答有帮助,并感谢您的好建议。 (2认同)
  • 不确定你是真的救了我的命还是只是象征性的,但不管怎样,谢谢你的回答。^^ +1 (2认同)

xav*_*did 3

来自 Zapier 平台团队的 David。

根据文档

output:将作为此代码的“返回值”的字典或字典列表。如果您愿意,您可以明确提前返回。这必须是 JSON 可序列化的!

在你的情况下,output是一个集合:

>>> output = {'Yes'}
>>> type(output)
<class 'set'>
>>> json.dumps(output)
Object of type set is not JSON serializable
Run Code Online (Sandbox Code Playgroud)

要可序列化,您需要一个字典(具有键和值)。更改最后一行以包含密钥,它将像您期望的那样工作:

#         \ here /
output = {'result': time_remaining_less_than_fourteen((input['year']), (input['month']), (input['day']))}
Run Code Online (Sandbox Code Playgroud)