I only have plpython3u
, but it should also work for Python 2.7 using plpythonu
(just change that part of the following and nothing else).
CREATE OR REPLACE FUNCTION GetWeather(lon float, lat float)
RETURNS float AS $$
import sys
if sys.version_info[0] == 2:
from urllib2 import urlopen
else: # Python 3
from urllib.request import urlopen
import json
def get_temp(lon, lat):
data = urlopen(
"http://api.openweathermap.org/data/2.1/find/station?lat=%s&lon=%s&cnt=1"
% (lat, lon))
js_data = json.loads(data.read().decode('utf-8'))
try:
return js_data['list'][0]['main']['temp']
except (KeyError, IndexError):
return None
return get_temp(lon, lat)
$$ LANGUAGE plpython3u;
Note that the above is with a 4-space indent convention (PEP 8). If you are new to Python, I'd recommend going through a few tutorials to understand the syntax and use of indents.