Search code examples
pythonjsonweatherweather-api

Python openweather, json - get weather by city name - how can I say that the city is incorrrect?


I found and modified simple code to get weather condition in Python using openweather and json format. But I have a problem - how can I say that the city is incorrect?

I mean even if I pass a wrong, nonexisting city, read always gives an answer (theres no such thing like 'empty response' or something like that).

See the code below to see what I'm talking about:

#!/usr/bin/python
# -*- coding: utf-8 -*-
import urllib2, json

city = "etre4t5r5e4re" # the city name is incorrent
url = "http://openweathermap.org/data/2.1/forecast/city?q="
url += city
try :
    request = urllib2.Request(url)
    response = urllib2.urlopen(request)
except urllib2.HTTPError, e:
    info = wx.MessageBox(u"Internet connection error", u"Error", wx.OK | wx.ICON_ERROR)
except urllib2.URLError, e:
    info = wx.MessageBox(u"Internet connection error", u"Error", wx.OK | wx.ICON_ERROR)
except httplib.HTTPException, e:
    info = wx.MessageBox(u"Internet connection error", u"Error", wx.OK | wx.ICON_ERROR)
except Exception:
    info = wx.MessageBox(u"Error", u"Error", wx.OK | wx.ICON_ERROR)
weather = response.read()

if __name__ == '__main__':
    print(weather) # it will show weather but thats not what I want for non-existing city!

Solution

  • There is a recurrent ID when the city requested doesn't exist, you can maybe based your code on that, or make a second request. I've explained the two solutions that I would have used.

    #!/usr/bin/python
    
    import urllib2, json
    
    city = "etre4t5r5e4re"
    root = "http://openweathermap.org/data/2.1/forecast/city?q=%s"
    url  = root % city
    
    response = urllib2.urlopen(url)
    j = json.load(response)
    
    # Solution 1
    if j.get('url', '').split('/')[-1] == '7284885':
        print " ! This city seems to be THE Unknown city"
    
    # Solution 2
    if 'No station' in urllib2.urlopen(j.get('url')).read():
        print " ! Again.. This city seems to be THE Unknown city"