Posted By

dedal on 01/24/10


Tagged

weather


Versions (?)

Weather show


 / Published in: Python
 

  1. #!/usr/bin/env python
  2. #-*- coding:utf-8 -*-
  3.  
  4. # Copyright 2009 Grigor Kolev <[email protected]>
  5. #
  6. # This program is free software; you can redistribute it and/or modify
  7. # it under the terms of the GNU General Public License as published by
  8. # the Free Software Foundation; either version 2 of the License, or
  9. # (at your option) any later version.
  10. #
  11. # This program is distributed in the hope that it will be useful,
  12. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  13. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  14. # GNU General Public License for more details.
  15. #
  16. # You should have received a copy of the GNU General Public License
  17. # along with this program; if not, write to the Free Software
  18. # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
  19. # MA 02110-1301, USA.
  20. #----------------------------------------------------------------------------------------------------------
  21. # These functions are taken from the module pywapy.
  22. # Created by Eugene Kaznacheev <[email protected]>
  23. #----------------------------------------------------------------------------------------------------------
  24.  
  25. import urllib2, re
  26. from xml.dom import minidom
  27. from urllib import quote
  28.  
  29. GOOGLE_WEATHER_URL = 'http://www.google.com/ig/api?weather=%s&hl=%s'
  30. GOOGLE_COUNTRIES_URL = 'http://www.google.com/ig/countries?output=xml&hl=%s'
  31. GOOGLE_CITIES_URL = 'http://www.google.com/ig/cities?output=xml&country=%s&hl=%s'
  32.  
  33. def get_weather_from_google(location_id, hl = ''):
  34. """
  35. Fetches weather report from Google
  36.  
  37. Parameters
  38. location_id: a zip code (10001); city name, state (weather=woodland,PA); city name, country (weather=london, england);
  39. latitude/longitude(weather=,,,30670000,104019996) or possibly other.
  40. hl: the language parameter (language code). Default value is empty string, in this case Google will use English.
  41.  
  42. Returns:
  43. weather_data: a dictionary of weather data that exists in XML feed.
  44. """
  45. location_id, hl = map(quote, (location_id, hl))
  46. url = GOOGLE_WEATHER_URL % (location_id, hl)
  47. handler = urllib2.urlopen(url)
  48. content_type = handler.info().dict['content-type']
  49. charset = re.search('charset\=(.*)',content_type).group(1)
  50. if not charset:
  51. charset = 'utf-8'
  52. if charset.lower() != 'utf-8':
  53. xml_response = handler.read().decode(charset).encode('utf-8')
  54. else:
  55. xml_response = handler.read()
  56. dom = minidom.parseString(xml_response)
  57. handler.close()
  58.  
  59. weather_data = {}
  60. weather_dom = dom.getElementsByTagName('weather')[0]
  61.  
  62. data_structure = {
  63. 'forecast_information': ('city', 'postal_code', 'latitude_e6', 'longitude_e6', 'forecast_date', 'current_date_time', 'unit_system'),
  64. 'current_conditions': ('condition','temp_f', 'temp_c', 'humidity', 'wind_condition', 'icon')
  65. }
  66. for (tag, list_of_tags2) in data_structure.iteritems():
  67. tmp_conditions = {}
  68. for tag2 in list_of_tags2:
  69. try:
  70. tmp_conditions[tag2] = weather_dom.getElementsByTagName(tag)[0].getElementsByTagName(tag2)[0].getAttribute('data')
  71. except IndexError:
  72. pass
  73. weather_data[tag] = tmp_conditions
  74.  
  75. forecast_conditions = ('day_of_week', 'low', 'high', 'icon', 'condition')
  76. forecasts = []
  77.  
  78. for forecast in dom.getElementsByTagName('forecast_conditions'):
  79. tmp_forecast = {}
  80. for tag in forecast_conditions:
  81. tmp_forecast[tag] = forecast.getElementsByTagName(tag)[0].getAttribute('data')
  82. forecasts.append(tmp_forecast)
  83.  
  84. weather_data['forecasts'] = forecasts
  85. dom.unlink()
  86.  
  87. return weather_data
  88.  
  89. def get_country_from_google(hl = ''):
  90. """
  91. Get list of countries in specified language from Google
  92.  
  93. Parameters
  94. hl: the language parameter (language code). Default value is empty string, in this case Google will use English.
  95. Returns:
  96. countries: a list of elements(all countries that exists in XML feed). Each element is a dictionary with 'name' and 'iso_code' keys.
  97. For example: [{'iso_code': 'US', 'name': 'USA'}, {'iso_code': 'FR', 'name': 'France'}]
  98. """
  99. url = GOOGLE_COUNTRIES_URL % hl
  100.  
  101. handler = urllib2.urlopen(url)
  102. content_type = handler.info().dict['content-type']
  103. charset = re.search('charset\=(.*)',content_type).group(1)
  104. if not charset:
  105. charset = 'utf-8'
  106. if charset.lower() != 'utf-8':
  107. xml_response = handler.read().decode(charset).encode('utf-8')
  108. else:
  109. xml_response = handler.read()
  110. dom = minidom.parseString(xml_response)
  111. handler.close()
  112.  
  113. countries = []
  114. countries_dom = dom.getElementsByTagName('country')
  115.  
  116. for country_dom in countries_dom:
  117. country = {}
  118. country['name'] = country_dom.getElementsByTagName('name')[0].getAttribute('data')
  119. country['iso_code'] = country_dom.getElementsByTagName('iso_code')[0].getAttribute('data')
  120. countries.append(country)
  121.  
  122. dom.unlink()
  123. return countries
  124.  
  125.  
  126. def get_cities_from_google(country_code, hl = ''):
  127. """
  128. Get list of cities of necessary country in specified language from Google
  129.  
  130. Parameters
  131. country_code: code of the necessary country. For example 'de' or 'fr'.
  132. hl: the language parameter (language code). Default value is empty string, in this case Google will use English.
  133. Returns:
  134. cities: a list of elements(all cities that exists in XML feed). Each element is a dictionary with 'name', 'latitude_e6' and 'longitude_e6' keys. For example: [{'longitude_e6': '1750000', 'name': 'Bourges', 'latitude_e6': '47979999'}]
  135. """
  136. url = GOOGLE_CITIES_URL % (country_code.lower(), hl)
  137.  
  138. handler = urllib2.urlopen(url)
  139. content_type = handler.info().dict['content-type']
  140. charset = re.search('charset\=(.*)',content_type).group(1)
  141. if not charset:
  142. charset = 'utf-8'
  143. if charset.lower() != 'utf-8':
  144. xml_response = handler.read().decode(charset).encode('utf-8')
  145. else:
  146. xml_response = handler.read()
  147. dom = minidom.parseString(xml_response)
  148. handler.close()
  149.  
  150. cities = []
  151. cities_dom = dom.getElementsByTagName('city')
  152.  
  153. for city_dom in cities_dom:
  154. city = {}
  155. city['name'] = city_dom.getElementsByTagName('name')[0].getAttribute('data')
  156. city['latitude_e6'] = city_dom.getElementsByTagName('latitude_e6')[0].getAttribute('data')
  157. city['longitude_e6'] = city_dom.getElementsByTagName('longitude_e6')[0].getAttribute('data')
  158. cities.append(city)
  159.  
  160. dom.unlink()
  161.  
  162. return cities
  163. #---------------------------------------------------------------------------------------------
  164.  
  165. class Error(Exception): #Създава мое изключение
  166.  
  167.  
  168. def __init__(self, value): #Конструктор създава инстанция стоиност на инстанция по подразбиране при извикване на класа
  169. self.value = value
  170.  
  171. def Value(self ): #Връща резултат на стоиноста на инстанцията
  172. return self.value
  173.  
  174.  
  175. class BadCountryCode(Error):
  176. pass
  177.  
  178.  
  179. class BadSityName (Error):
  180. pass
  181.  
  182.  
  183. class Country ():
  184. '''
  185. Take the Countri list with country code.
  186. '''
  187.  
  188. def __init__(self):
  189. self.data = get_country_from_google()
  190. a = 0
  191. tmp = {}
  192. for i in self.data:
  193. a +=1
  194. tmp[a] = i
  195. self.data = tmp
  196.  
  197. def show(self ):
  198. for i in self.data.values():
  199. print '\n'
  200. for keys in i.keys():
  201. print keys, '.'*10, i[keys]
  202.  
  203. def get(self ):
  204. return self.data
  205.  
  206.  
  207. class Sity (Country):
  208.  
  209. def __init__(self, country_code = None):
  210. try:
  211. self.data = get_cities_from_google(country_code)
  212. tmp = {}
  213. a = 0
  214. for i in self.data:
  215. a+=1
  216. tmp[a] = i.get('name')
  217. self.data = tmp
  218. if len(self.data) == 0:
  219. raise BadCountryCode, 'Invalid country code. You can see all available iso_code with: country = Country() country.show()'
  220. except AttributeError:
  221. print 'You must select country code \nYou can see all available iso_code with: \ncountry = Country() \ncountry.show()'
  222.  
  223. def show(self):
  224. for keys in self.data.keys():
  225. print keys,'.'*10, self.data.get(keys)
  226.  
  227.  
  228. class Weather (Sity):
  229.  
  230. def __init__(self, sity_name = None):
  231. try:
  232. self.data = get_weather_from_google(sity_name)
  233. tmp = {}
  234. tmp['Sity'] = (sity_name)
  235. tmp['temp_c'] = self.data.get('current_conditions').get('temp_c')
  236. tmp['temp_f'] = self.data.get('current_conditions').get('temp_f')
  237. self.data = tmp
  238. if self.data['temp_c'] == None:
  239. raise BadSityName, 'Wrong or not available on a city name. You can see all available sity with: sity = Sity() sity.show()'
  240. except TypeError:
  241. print 'You must write the name of the sity.\nYou can see all available sity with:\nsity = Sity()\nsyty.show()'
  242.  
  243.  
  244. if __name__ == '__main__':
  245. weather = Weather('Varna')
  246. weather.show()
  247. raw_input()

Report this snippet  

You need to login to post a comment.