Weather Api Не работает фильтр правильных/неправильных городов (проект Django - файл views.py ниже)

weatherapi.com дает мне два разных ответа для города, который существует или города, которого нет

#когда я пытаюсь добавить неправильный город, я получаю следующее воспроизведение из api. {'error': {'code': 1006, 'message': 'No matching location found.'}}

#когда я пишу правильное название города, я получаю такой ответ от api. {'location': {'name': 'Texas City', 'region': 'Texas', 'country': 'United States of America', 'lat': 29.38, 'lon': -94.9, 'tz_id': 'Америка/Чикаго', 'localtime_epoch': 1670842210, 'localtime': '2022-12-12 4:50'}, 'current': { 'last_updated_epoch': 1670841900, 'last_updated': '2022-12-12 04:45', 'temp_c': 18.9, 'temp_f': 66.0, 'is_day': 0, 'condition': {'text': 'Overcast', 'icon': '//cdn.weatherapi.com/weather/64x64/night/122.png', 'code': 1009}, 'wind_mph': 9.4, 'wind_kph': 15.1, 'wind_degree': 60, 'wind_dir': 'ENE', 'pressure_mb': 1016.0, 'pressure_in': 30.01, 'precip_mm': 0.0, 'precip_in': 0.0, 'влажность': 93, 'облачность': 100, 'feelslike_c': 18.9, 'feelslike_f': 66.0, 'vis_km': 11.0, 'vis_miles': 6.0, 'uv': 1.0, 'gust_mph': 10.1, 'gust_kph': 16.2, 'air_quality': {'co': 260.3999938964844, 'no2': 17.0, 'o3': 1.100000023841858, 'so2': 6.5, 'pm2_5': 4.0, 'pm10': 5.800000190734863, 'us-epa-index': 1, 'gb-defra-index': 1}}}

Как отфильтровать с помощью "code: 1006", что город существует или не существует перед сохранением в базу данных?

Код A работает нормально, если город не существует, но показывает ошибку ключа, если добавить нужный город

код B работает, если я добавляю город, который существует, но если я пытаюсь добавить город, который не существует, показывает Eror key error condition

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)

Сначала вы должны проверить, является ли это случай ошибки или случай успеха в качестве ответа от API погоды, затем соответственно вы можете обрабатывать эти случаи. Я не использовал try catch в приведенном ниже коде, который вы можете обновить, чтобы сделать его более надежным, также я изменил проверку существования города в базе данных с count на exists, так как это более эффективный способ. Пожалуйста, проверьте закомментированные части, я упомянул детали там и не стесняйтесь подключать любые дополнительные детали, необходимые. пожалуйста, проголосуйте, если мой ответ помог вам спасибо и счастливого кодирования!!! :)

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()})
Вернуться на верх