djangoapiweather

Weather Api Right/wrong city filter not working (Django project - views.py file below)


weatherapi.com giving me two different replies for city that exist or city that does not exist

#when i am trying to add Wrong city i am getting this replay from api. {'error': {'code': 1006, 'message': 'No matching location found.'}}

#when i am writing right city name i am geting this reply from api. {'location': {'name': 'Texas City', 'region': 'Texas', 'country': 'United States of America', 'lat': 29.38, 'lon': -94.9, 'tz_id': 'America/Chicago', '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, 'humidity': 93, 'cloud': 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}}}

How can i filter by using "code: 1006" that city exist or not exist before saving it to database?

Code A working fine if city does not exist but showing key error if add a right city

code B working if I add city that exist but if i try to add a city does not exist, showing 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)


Solution

  • First you have to check whether its an error case or success case as response from weather API then accordingly you can handle the cases. i have not used try catch in below code which you can update further to make it more robust also i have changed the city existence check in db from count to exists as it is more efficient way. Please check commented parts i have mentioned details there and feel free to connect any further details required. please upvote if my answer helped you thanks and happy coding!! :)

    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()})