Skip to content

Commit

Permalink
Merge pull request #11 from DeliangFan/error-handler
Browse files Browse the repository at this point in the history
Hander the error
  • Loading branch information
DeliangFan committed May 20, 2015
2 parents 5970022 + b791343 commit c29fc84
Showing 1 changed file with 20 additions and 11 deletions.
31 changes: 20 additions & 11 deletions we.py
Original file line number Diff line number Diff line change
Expand Up @@ -188,7 +188,7 @@
5: '220',
6: '214',
7: '208',
9: '202',
8: '202',
}


Expand Down Expand Up @@ -234,8 +234,8 @@ def get_wind_icon(self):
return wind_icon

def color_wind(self, wind_speed):
if int(wind_speed * 1.2) >= 9:
color = WIND_COLOR[9]
if int(wind_speed * 1.2) >= 8:
color = WIND_COLOR[8]
else:
color = WIND_COLOR[int(wind_speed * 1.2)]

Expand Down Expand Up @@ -302,30 +302,33 @@ def __init__(self, q=None):
self.today_path = '/data/2.5/forecast/daily?units=metric&cnt=15&q=' + self.q

def http_request(self, path):
# try:... We need handle exception here.

conn = httplib.HTTPConnection(self.host)
conn.request('GET', path)
try:
conn = httplib.HTTPConnection(self.host)
conn.request('GET', path)
except Exception as ex:
print_exit_error(ex)

res = conn.getresponse()
if res.status in (200, 201, 202, 204):
if res.status in OK_STATUS:
body = res.read()
else:
body = None
msg = "Network Problem: please try again later ^_^."
print_exit_error(msg)

conn.close()

return body

def get_weather_data(self):
resp = self.http_request(self.today_path)
# TypeError: expected string or buffer

if not resp:
exit(0)
print_exit_error("Response data is None.")

data = json.loads(resp)

if data['cod'] == "404":
print_exit_error("Sorry, the city is not found.")

self.city = data['city']['name']
self.country = data['city']['country']
Expand Down Expand Up @@ -373,6 +376,12 @@ def print_city_info(city, country):
print(city_info)


def print_exit_error(msg):
msg = "\033[31m" + msg + "\033[0m"
print(msg)
exit(-1)


if '__main__' == __name__:
if len(sys.argv) == 1:
weather = OpenWeatherMap()
Expand Down

0 comments on commit c29fc84

Please sign in to comment.