城市名称中的KeyError

时间:2019-07-24 14:04:15

标签: django openweathermap

我在Django中制作了一个小型气象网络应用程序,并且运行正常,但是 输入错误的城市名称后,它将开始显示KeyError页面。

from django.shortcuts import render, redirect
from django.contrib import messages
import requests

#search page
def search(request):
    return render(request, 'index.html')

#forecast result page
def forecast(request):
    c = request.POST['city']
    url = 'http://api.openweathermap.org/data/2.5/weather?q={}&appid=7fee53226a6fbc936e0308a3f4941aaa&units=metric'.format(c)
    r = requests.get(url)
    data = r.json()
    weather = {
        'description': data['weather'][0]['description'],
        'icon': data['weather'][0]['icon'],
        'city': c.title(),
        'temperature': data['main']['temp']
            }
    print(r)
    return render(request, 'weather.html', {'weather': weather})

在输入错误的城市名称时,它会给出KeyError,所以我希望与其给出KeyError,而不是django将其重定向到我的首页,即index.html,并在其下方显示错误消息。

2 个答案:

答案 0 :(得分:1)

API会告诉您城市名称是否无效。

r = requests.get(url)
if r.status_code == 404:
    messages.add_message('City not found')
    return redirect('home')
data = r.json()
...

答案 1 :(得分:0)

首先,请构造自己的查询集: querystrings 不能包含很多字符。您可以为此使用Django的QueryDict

from django.http import QueryDict

qd = QueryDict(mutable=True)
qd.update(q=c, appid='7fee53226a6fbc936e0308a3f4941aaa', units='metric')
url = 'http://api.openweathermap.org/data/2.5/weather?{}'.format(qd.urlencode())

对于'New York'之类的城市,它将编码为:

>>> qd.urlencode()
'q=New+York&appid=7fee53226a6fbc936e0308a3f4941aaa&units=metric'

因此它用+替换了空格。

此外,您可以在此处使用try-except重定向到另一个页面,例如:

from django.http import QueryDict
from django.shortcuts import redirect

def forecast(request):
    try:
        city = request.POST['city']
    except:
        return redirect('name-of-some-view')
    qd = QueryDict(mutable=True)
    qd.update(q=city, appid='7fee53226a6fbc936e0308a3f4941aaa', units='metric')
    url = 'http://api.openweathermap.org/data/2.5/weather?{}'.format(qd.urlencode())
    try:
        data = r.json()
        weather = {
            'description': data['weather'][0]['description'],
            'icon': data['weather'][0]['icon'],
            'city': c.title(),
            'temperature': data['main']['temp']
        }
    except KeyError:
        return redirect('name-of-some-view')
    return render(request, 'weather.html', {'weather': weather})

您可以使用Django Messages Framework [Django-doc]向用户显示消息。

相关问题