如何解决Django-处理KeyError事件API
我用Python / Django制作了一个小天气应用程序。我从openweathermap.org获取了实际的天气数据。我设置了项目,创建了搜索字段以搜索城市并使用API进行连接,然后一切正常,直到您输入错误的字母(例如chikago)为止。然后我得到一个KeyError。
在这里您可以看到我的代码 views.py
const mongoose = require("mongoose");
const sellerSchema = new mongoose.Schema({
name:{
type: String,required: true,},type: {
type: String,required: true
},location: {
type: {
type: "String",enum:['Point']
},coordinates: {
type: [Number],index: '2dsphere'
}
},owner: {
type: String,items: [{
type: mongoose.Schema.Types.ObjectId,ref: "items"
}],contact: {
type: String,loginId: {
index:true,unique: true,type: String,password: {
type: String,createdAt: {
type: Date,default: Date.now
}
});
const sellerModel = mongoose.model("sellers",sellerSchema);
module.exports = sellerModel;
如果我查看检查器,则会看到错误404,因此我尝试在基本urls.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})
,但没有捕获到内部错误。还有openweathermap响应,错误消息为404:handle404
。
有没有办法将错误消息处理到div中?
解决方法
您可以使用.status_code
属性查看请求的响应代码
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")
,
需要将请求转换为json对象。我无法详细编写代码,因为上面已共享了它。 祝你好运
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。