简体   繁体   English

递归 function 调用无法在 AWS Lambda 中递归 - Python3

[英]Recursive function call fails to recurse in AWS Lambda - Python3

Im trying to replace python dictionary key with a different key name recursively for which i am using aws lambda with a api endpoint to trigger.我试图用不同的键名递归地替换 python 字典键,为此我使用 aws lambda 和 api 端点来触发。 Suprisingly the recursion part fails for weird reason.令人惊讶的是递归部分由于奇怪的原因而失败。 The same code works fine in local.相同的代码在本地工作正常。

Checked cloudwatch logs.检查了 cloudwatch 日志。 No error message get displayed there.那里没有显示错误消息。 Let me know if im missing anything here如果我在这里遗漏任何东西,请告诉我

EDIT: Related to Unable to invoke a recursive function with AWS Lambda and recursive lambda function never seems to run编辑:与Unable to invoke a recursive function with AWS Lambdarecursive lambda function never seems to run 有关

### function that is called inside lambda_handler

def replace_recursive(data,mapping):
    for dict1 in data:
        for k,v in dict1.copy().items():
            if isinstance(v,dict):
                dict1[k] = replace_recursive([v], mapping)
            try:
                dict1[mapping['value'][mapping['key'].index(k)]] = dict1.pop(mapping['key'][mapping['key'].index(k)])
            except KeyError:
                continue
    return data
## lambda handler

def lambda_handler(events,_):
    resp = {'statusCode': 200}
    parsed_events = json.loads(events['body'])
    if parsed_events:
        op = replace_recursive(parsed_events,schema)
        resp['body'] = json.dumps(op)
    return resp

Input I pass:输入我通过:

{
  "name": "michael",
  "age": 35,
  "family": {
    "name": "john",
    "relation": "father"
  }
}

In the output, keys in the nested dictionary are not getting updated.在 output 中,嵌套字典中的键没有得到更新。 Only outer keys get modified只有外键被修改

Since you're ingesting JSON, you can do the key replacement right in the parse phase for a faster and simpler experience using the object_pairs_hook argument to json.loads .由于您正在摄取 JSON,因此您可以使用json.loadsobject_pairs_hook参数在解析阶段进行密钥替换,以获得更快、更简单的体验。

import json

key_mapping = {
    "name": "noot",
    "age": "doot",
    "relation": "root",
}


def lambda_handler(events, _):
    replaced_events = json.loads(
        events["body"],
        object_pairs_hook=lambda pairs: dict(
            (key_mapping.get(k, k), v) for k, v in pairs
        ),
    )
    return {
        "statusCode": 200,
        "body": json.dumps(replaced_events),
    }


body = {
    "name": "michael",
    "age": 35,
    "family": {"name": "john", "relation": "father"},
}
print(
    lambda_handler(
        {
            "body": json.dumps(body),
        },
        None,
    )
)

prints out打印出来

{'statusCode': 200, 'body': '{"noot": "michael", "doot": 35, "family": {"noot": "john", "root": "father"}}'}

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

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