2012-12-07 52 views
3

我找到並修改了簡單的代碼,以便使用openweather和json格式在Python中獲取天氣狀況。但我有一個問題 - 我怎麼說這個城市是不正確的?Python openweather,json - 通過城市名稱獲取天氣 - 我怎麼說這個城市是不正確的?

我的意思是,即使我通過一個錯誤的,不存在的城市,閱讀總是給出一個答案(theres沒有這樣的事情像'空迴應'或類似的東西)。

請參見下面的代碼,看看我說的是:

#!/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! 
+1

的URL通過'http://openweathermap.org/data/2.1/forecast/city Q = etre4t5r5e4re'返回'內部服務器錯誤未定義指數:geonames_id'我。 –

+1

當我試圖得到不正確的城市信息時,該服務給了我莫斯科。 – alexvassel

+0

@NiclasNilsson:奇怪,因爲我實際上得到這個輸出:http://pastebin.com/aa1q6DBK沒有錯誤o_O – mazix

回答

1

有要求時,這個城市不存在復發的ID,你也許可以根據你的代碼,或進行第二個請求。我已經解釋了我會用到的兩種解決方案。

#!/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"