【发布时间】:2022-11-22 23:05:07
【问题描述】:
我有以下事件主体(字典)进入 lambda 函数,我做了类似下面的事情:
{
"test-report": {
"document-uri": "http://example.com/index.html",
"original-policy": "default-src 'none'; style-src example.com; report-uri /_/test-reports"
}
}
if 'test-report' in event['body']:
try:
do something here
我的问题是我想在字典的第一个对象中检查test-report。如果不匹配,我不希望该函数执行任何操作。但是,如您所见,**test-report**s 也出现在 original-policy 值下,我不想在我的 if 语句中考虑这些值。
更新:
这是完整的请求上下文。
{
"requestContext":{
"elb":{
"targetGroupArn":"arn:aws:elasticloadbalancing:us-east-2:xxxxxx:targetgroup/lambda-xxxxxxx/xxxxxxx"
}
},
"httpMethod":"POST",
"path":"/lambda",
"queryStringParameters":{
"query":"1234ABCD"
},
"headers":{
"accept":"text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8",
"accept-encoding":"gzip",
"accept-language":"en-US,en;q=0.9",
"connection":"keep-alive",
"host":"alb.com",
"upgrade-insecure-requests":"1",
"user-agent":"test",
"x-amzn-trace-id":"Root=1-xxxxxxxxxxxx",
"x-forwarded-for":"x.x.x.x",
"x-forwarded-port":"80",
"x-forwarded-proto":"http",
"x-imforwards":"20"
},
"body":{
"test-report": {
"document-uri": "http://example.com/index.html",
"original-policy": "default-src 'none'; style-src example.com; report-uri /_/test-reports"
}
},
"isBase64Encoded":false
}
【问题讨论】:
-
要重现该问题,示例代码缺少
body。请更新响应事件 -
字典的
in运算符只是测试是否有匹配的键,它不会更深入。我没有看到问题。 -
'test-report' in event['body']检查event['body']是否有键'test-report'(假设event['body']是一个字典) -
当您在字典上使用
in时,它只会检查钥匙;它不检查价值观.所以这应该完全按照你的意愿工作。 (但是,大概你遇到了某种问题,否则你不会发布这个问题,所以看来你需要解释更多......) -
感谢大家。是的,正文是一本字典。我更新了问题。
标签: python python-3.x lambda