Django句柄KeyError事件(API)

2024-05-11 14:29:34 发布

您现在位置:Python中文网/ 问答频道 /正文

我用Python/Django制作了一个小天气应用程序。我从openweathermap.org获取了实际的天气数据。我设置了我的项目,创建搜索字段来搜索城市,并与API连接,一切正常。。直到您键入错误的字母(例如chikago)。然后我得到一个键错误。 enter image description here

在这里你可以看到我的代码 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中


Tags: keypyorgimportapicityindexrequest
2条回答

需要将请求转换为json对象。我无法编写详细的代码,因为它是上面共享的。 祝你好运

您可以使用^{}属性检查请求的响应代码

from django.shortcuts import render
from django.http import HttpResponse
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')

    request_response = requests.get(API_KEY.format(city))
    if request_response.status_code == 200:
        res = request_response.json()
        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})
    else:
        return HttpResponse("Not Found")

相关问题 更多 >