f69f1e288bb94de67507ec43164c072230cf5446
[vuplus_xbmc] / addons / weather.wunderground / resources / lib / wunderground / wunderground.py
1 # -*- coding: utf-8 -*-
2
3 import urllib2, gzip, base64
4 from StringIO import StringIO
5
6 WAIK             = 'NDEzNjBkMjFkZjFhMzczNg=='
7 WUNDERGROUND_URL = 'http://api.wunderground.com/api/%s/%s/%s/q/%s.%s'
8 API_EXCLUDE      = ['hourly10day', 'yesterday', 'planner', 'webcams', 'animatedradar', 'animatedsatellite', 'currenthurricane']
9
10 def wundergroundapi(features, settings, query, format):
11
12     """
13     wunderground api module
14     
15     How to use:
16     
17     1) import the wunderground addon in your addon.xml:
18             <requires>
19                 <import addon="weather.wunderground" version="0.1.12"/>
20             </requires>
21     
22     2) import the wunderground api module in your script:
23             from wunderground import wundergroundapi
24     
25     3) to fetch weather data:
26             weatherdata = wundergroundapi(features, settings, query, format)
27     
28     see http://www.wunderground.com/weather/api/d/docs?d=data/index
29     for api features, optional settings, query examples and response formats.
30     """
31
32     for item in API_EXCLUDE:
33         if item in features:
34             return 'api access to %s restricted' % item
35     if not settings:
36         settings = 'lang:EN'
37     url = WUNDERGROUND_URL % (base64.b64decode(WAIK)[::-1], features, settings, query, format)
38     try:
39         req = urllib2.Request(url)
40         req.add_header('Accept-encoding', 'gzip')
41         response = urllib2.urlopen(req)
42         if response.info().get('Content-Encoding') == 'gzip':
43             buf = StringIO(response.read())
44             compr = gzip.GzipFile(fileobj=buf)
45             data = compr.read()
46         else:
47             data = response.read()
48         response.close()
49     except:
50         data = ''
51     return data