PyMetOffice  0.4
Pythonic access to UK Met Office DataPoint API
forecast.py
1 #!/usr/bin/python
2 
3 import base
4 import json
5 import constants
6 import places
7 
9  def _getRawForecastData(self, period, site, **other):
10  params = other
11  params['res'] = period
12  (d, u) = self._makeApiRequest('public',
13  'data',
14  'val',
15  'wxfcs',
16  'all',
17  'json',
18  site,
19  **params)
20  return json.loads(d)
21 
22  ## This returns a dictionary in a suitable form for
23  # translating the Met Office observation/forecast items
24  # into more user-friendly names.
25  def makeDecoder(self, data):
26  d = data['SiteRep']['Wx']['Param']
27  result = {}
28  for item in d:
29  result[item['name']] = (item['$'], item['units'])
30  return result
31 
32  def _translateUnits(self, fcdata, decoder):
33  result = []
34  for rep in fcdata:
35  # Two values need decoding.
36  rep['V'] = constants.VISIBILITY[rep['V']]
37  rep['W'] = constants.WEATHER_TYPES[int(rep['W'])]
38  tmp = []
39  for k in rep.keys():
40  if k != '$':
41  tmp.append((decoder[k][0], rep[k], decoder[k][1]))
42  tmp.sort()
43  result.append((rep['$'], tmp))
44  result.sort()
45  return result
46 
47 
48  def _getDailyForecastData(self, site, **params):
49  result = []
50  data = self._getRawForecastData('daily', site, **params)
51  dv = data['SiteRep']['DV']['Location']['Period']
52  decoder = self.makeDecoder(data)
53  for fc in dv:
54  fcdata = fc['Rep']
55  date = fc['value']
56  fcast = self._translateUnits(fcdata, decoder)
57  result.append((date, fcast))
58  return result
59 
60  def _get3HourlyForecastData(self, site, **params):
61  result = []
62  data = self._getRawForecastData('3hourly', site, **params)
63  dv = data['SiteRep']['DV']['Location']['Period']
64  decoder = self.makeDecoder(data)
65  for fc in dv:
66  fcdata = fc['Rep']
67  date = fc['value']
68  fcast = self._translateUnits(fcdata, decoder)
69  result.append((date, fcast))
70  return result
71 
72  def getDailyForecastPlace(self, place, index=0):
73  pls = places.PlaceSet(place)
74  data = pls.places[index].getLatLon()
75  return self._getDailyForecastData('nearestlatlon', **data)
76 
77  def get3HourlyForecastPlace(self, place, index=0):
78  pls = places.PlaceSet(place)
79  data = pls.places[index].getLatLon()
80  return self._get3HourlyForecastData('nearestlatlon', **data)
81 
82  def getDailyForecastId(self, id):
83  data = self._getDailyForecastData(id, **{})
84  return data
85 
86  def get3HourlyForecastId(self, id):
87  data = self._get3HourlyForecastData(id, **{})
88  return data
89 
90