AWS Lambda 事件字典以非标准方式运行?

AWS Lambda event dict behaving in a non-standard way?

考虑以下代码:

def handle_lambda(event, context):
    multivalue_params = event.get('multiValueQueryStringParameters', {})
    print(multivalue_params)
    print(type(multivalue_params).__name__)
    print(type(event).__name__)

输出:

None
NoneType
dict

什么给了?为什么字典默认参数对事件字典不起作用?是否有我遗漏的最佳实践?

那个键存在时,这对于字典来说是非常正常的行为:

>>> event = {'multiValueQueryStringParameters': None}
>>> multivalue_params = event.get('multiValueQueryStringParameters', {})
>>> print(multivalue_params)
None
>>> print(type(multivalue_params).__name__)
NoneType
>>> print(type(event).__name__)
dict

dict.get 只有 returns 键 根本不存在 时的默认参数。你可能想要这样的东西:

# be prepared for both non-existent keys and None values:
multivalue_params = event.get('multiValueQueryStringParameters') or {}

# or expect the key to exist but to potentially be None:
multivalue_params = event['multiValueQueryStringParameters']
if multivalue_params is not None:
    # process only in this case