天气API正确/错误城市过滤器不工作(Django项目-views.py文件如下)

5sxhfpxr  于 2022-12-20  发布在  Go
关注(0)|答案(1)|浏览(111)

weatherapi.com 给我两个不同的答复城市存在或城市不存在

#当我尝试添加错误的城市时,我从API得到此重播。('error':{“代码”:1006,“消息”:'未找到匹配位置。'}}
#当我写正确的城市名称时,我得到了来自API的回复。{'location':{'名称':'德克萨斯市','地区':“得克萨斯”,“国家”:“美利坚合众国”、“拉丁美洲”:29.38,“隆”:-94.9,“tz_id”:“美洲/芝加哥”、“本地时间_纪元”:1670842210,“当地时间”:'2022年12月12日4:50'},'当前':{“最后更新的时间点”:1670841900,“最后更新日期”:“2022年12月12日04:45”,“温度_c”:18.9,“温度_f”:66.0,“是_天”:0,“条件”:{'文本':'覆盖','图标':“天气预报”,“代码”:1009},“风速_英里/小时”:9.4,“风速/小时”:15.1,“风力_度”:60,“风向”:“ENE”、“压力_mbs”:1016.0,“输入压力":30.01,“精密度_mm”:0.0,“沉淀_in”:0.0,“湿度”:93、“云”:100,“感觉像_c”:18.9,“感觉像f”:66.0,“维斯_公里”:11.0,“维斯_英里”:6.0,“紫外线”:1.0,“阵风_英里/小时”:10.1,“阵风_kph”:16.2,“空气质量”:{“公司”:260.3999938964844,“编号2”:17.0,“o3”:1.100000023841858,“二氧化硫”:6.5,“pm2_5”:4.0,“pm10”:5.800000190734863,“美国环保署索引”:1,“gb-定义-索引”:1}}
如何使用“code:1006”保存到数据库之前城市是否存在?
代码A如果城市不存在,则工作正常,但如果添加正确的城市,则显示关键错误
代码B如果我添加存在的城市,但如果我尝试添加不存在的城市,则运行,显示错误键错误条件

from django.shortcuts import render
import requests
from .models import City
from .forms import CityForm

# Create your views here.

def index (request):
    url = 'http://api.weatherapi.com/v1/current.json?key=403d3701b46c42a2bac104734221012&q={}&aqi=yes'
    if request.method == 'POST':
        form = CityForm(request.POST)
        if form.is_valid():
            new_city = form.cleaned_data['name']
            existing_city_count= City.objects.filter(name = new_city).count()
            if existing_city_count ==0:
                r=requests.get(url.format(new_city)).json()
                
                #Code A ___________
                #error_code = r['error']['code'] == 1006:
                #if error_code = 1006:
                    #print("City does not exist")
                #else:
                    #form.save()
                    
                #Code B _____________   
                #right_code = r['current']['condition']['code']
                #if right_code is not 1006:
                    #form.save()
                #else:
                    #print("city does not exist")
            else:
                err_msg = "City Already exist in the database"
    
    
    form = CityForm()
    cities = City.objects.all()
    wd = []
    for city in cities:
        r = requests.get(url.format(city)).json()
        cw ={
            'city' : r['location']['name'],
            'temp' : r['current']['temp_c'],
            'desc' : r['current']['condition']['text'],
            'icon' :r['current']['condition']['icon'],
            'code' : r['current']['condition']['code'],
            }
        wd.append(cw)
        #print(wd)
    
    context = { 'cw':wd, 'addform': form}
    
    return render(request, 'wa/index.html', context)
ssgvzors

ssgvzors1#

首先,您必须检查是否是错误情况或成功情况,作为天气API的响应,然后相应地您可以处理这些情况。我没有在以下代码中使用try catch,您可以进一步更新以使其更健壮,我还将db中的城市存在检查从计数更改为存在,因为这是更有效的方式。请检查我在那里提到详细信息的注解部分并随时连接所需的任何进一步的细节。请upvote如果我的答案帮助你谢谢和快乐编码!!:)

from django.shortcuts import render
from .forms import CityForm
import requests
from .models import City

# Create your views here.
def index(request):
    url = 'http://api.weatherapi.com/v1/current.json?key=403d3701b46c42a2bac104734221012&q={}&aqi=yes'
    if request.method == 'POST':
        code=''
        form = CityForm(request.POST)
        if form.is_valid():
            new_city = form.cleaned_data['city']
            # existing_city_count= City.objects.filter(city = new_city).count() remove count and used exist to check whether a city exist in database or not as exist is more efficient that count
            if not City.objects.filter(city = new_city).exists():
                r=requests.get(url.format(new_city)).json()
                #Code A ___________
                if 'error' in r:#checking the key error exist  in response from get  or not
                    code = r['error']['code']
                #Code B _____________   
                if 'current' in r: #checking the key current exist  in result  or not
                    code =  r['current']['condition']['code']

                if code != 1006: #checking if code is not 1006 save city to database
                    form.save()      
                else:
                    print("city does not exist")
            else:
                err_msg = "City Already exist in the database"
            return render(request,'index.html',{'form':CityForm()})
    else:
       return render(request,'index.html',{'form':CityForm()})

相关问题