我用Python/Django制作了一个小天气应用程序。我从openweathermap.org获取了实际的天气数据。我设置了我的项目,创建搜索字段来搜索城市,并与API连接,一切正常。。直到您键入错误的字母(例如chikago)。然后我得到一个键错误。
在这里你可以看到我的代码 views.py
from django.shortcuts import render
import requests
def index(request):
API_KEY = 'http://api.openweathermap.org/data/2.5/weather?q={}&units=metric&appid=123456789'
city = request.POST.get('search_input')
res = requests.get(API_KEY.format(city)).json()
if city == '':
city = 'Berlin'
city_weather = {
'city': res['name'],
'temperature': res['main']['temp'],
'description': res['weather'][0]['description'],
'icon': res['weather'][0]['icon']
}
return render(request, 'weather/index.html', {'data': city_weather})
如果我查找inspector,我会看到一个错误404,因此我尝试在base url.py中添加一个handle404
,但它没有捕获内部错误。还有openweathermap响应,其中包含错误404消息:res {'cod': '404', 'message': 'city not found'}
有没有办法将错误消息处理到div中
需要将请求转换为json对象。我无法编写详细的代码,因为它是上面共享的。 祝你好运
您可以使用^{} 属性检查请求的响应代码
相关问题 更多 >
编程相关推荐