Use openweathermap module in web app.
[chrisu/seepark.git] / web / seepark_web.py
index ce4347fb315e793e791f84151c17d1d1e6281ff7..c0fd440d4da1e5f770c954fdb2d7c6ecc4295c29 100644 (file)
@@ -3,11 +3,15 @@ import datetime
 import time
 import configparser
 import os
+import sys
 from flask import Flask, render_template, jsonify, request
 import flask.json
 from sqlalchemy import create_engine
 import requests
 
+sys.path.append('..')
+from seeparklib.openweathermap import openweathermap_json, OpenWeatherMapError
+
 
 class JSONEncoder(flask.json.JSONEncoder):
     def default(self, object):
@@ -97,18 +101,12 @@ def select_sensordata(initial_where, initial_sql_args):
 
 
 def currentairtemperature(apikey, cityid):
-    baseurl = 'http://api.openweathermap.org/data/2.5/weather'
-    query = baseurl + '?units=metric&APPID={}&id={}&lang=de'.format(apikey, cityid)
+    """Retruns the tuple temperature, datetime (as float, datetime) in case of success, otherwise None, None."""
     try:
-        response = requests.get(query)
-        if response.status_code != 200:
-            response = 'N/A'
-            return response, datetime.datetime.now().strftime('%Y-%m-%d %H:%M')
-        else:
-            weatherdata = response.json()
-            return weatherdata['main']['temp'], datetime.datetime.fromtimestamp(weatherdata['dt']).strftime('%Y-%m-%d %H:%M')
-    except requests.exceptions.RequestException as error:
-        print (error)
+        weatherdata = openweathermap_json(apikey, cityid)
+        return weatherdata['main']['temp'], datetime.datetime.fromtimestamp(weatherdata['dt'])
+    except OpenWeatherMapError:
+        return None, None
 
 
 def currentwatertemperature(sensorid):