问题描述
import json
from botocore.vendored import requests
#import requests
def weatherfunc(city_name):
api_key = 'e914e5e16947fe541140de82a88e5888'
base_url = 'http://api.openweathermap.org/data/2.5/weather?'
finalurl = base_url + 'appid=' + api_key + '&q=' + city_name
response = requests.get(finalurl)
x = response.json()
y = x['main']
current_temperature = y['temp']
current_pressure = y['pressure']
current_humidiy = y['humidity']
z = x['weather']
weather_description = z[0]['description']
return {
'current temp': current_temperature,'humidity': current_humidiy,'pressure': current_pressure,'description': weather_description,}
def lambda_handler(event,context):
city = event['City']
a = weatherfunc(city)
return (a)
我想将天气信息返回给我的lex机器人,遇到错误: 响应: { “ errorMessage”:“'城市'”, “ errorType”:“ KeyError”, “堆栈跟踪”: [ “ lambda_handler中的文件“ /var/task/lambda_function.py”,第28行\ n city = event ['City'] \ n“ ] }
解决方法
根据错误消息:
- 您致电
lambda_handler
(在lambda_handler中) - ...该函数遇到了
KeyError
(“ errorType”:“ KeyError”) - ...位于
line 28
,即:city = event['City']
(第28行,city = event ['City'])
在KeyError python doc
上进行30秒的google搜索,您会发现this网站记录了KeyError。
此网站上的第一行相关内容为:Raised when a mapping (dictionary) key is not found in the set of existing keys.
请检查在请求中传递的事件内容,以正确获取城市名称。如果您从lex的事件内容中获取City,则可能是这样-city = event ['currentIntent'] ['slot'] ['city']。请参阅活动内容。