SyntaxError:语法无效(<string>)</string>

时间:2014-03-16 22:09:47

标签: python python-2.7 postgresql-9.1 postgis plpython

我有python 2.7并且我有返回温度信息的天气脚本,我想将这个脚本实现到PostgreSQL中。我总是遇到这个错误:DETAIL: SyntaxError: invalid syntax (<string>, line 10)

代码:

    CREATE OR REPLACE FUNCTION GetWeather(lon float, lat float)
    RETURNS float
    AS $$
    import urllib2
    import simplejson as json

    data = urllib2.urlopen(
    "http://api.openweathermap.org/data/2.1/find/station?lat=%s&lon=%s&cnt=1"% (lat, lon))
    js_data = json.load(data)
    if js_data['cod'] == '200': 
    if int(js_data['cnt'])>0: 
    station = js_data['list'][0] 
    print 'Data from weather station %s' %station['name']
    if 'main' in station: 
    if 'temp' in station['main']: 
    temperature = station['main']['temp'] - 273.15 
    else:temperature = None
    else:temperature = None

    return temperature

    $$ LANGUAGE plpythonu;

我也尝试了这个版本,但它无效

CREATE OR REPLACE FUNCTION GetWeather(lon float, lat float)
    RETURNS float
    AS $$
    import urllib2
    import simplejson as json

    def get_temp(lat, lon):
    data = urllib2.urlopen(
    "http://api.openweathermap.org/data/2.1/find/station?lat=%s&lon=%s&cnt=1"% (lat, lon))
    js_data = json.load(data)
    try:
    return js_data['list'][0]['main']['temp']
    except (KeyError, IndexError):
        return None

    $$ LANGUAGE plpythonu;

2 个答案:

答案 0 :(得分:1)

我只有plpython3u,但它也适用于使用plpythonu的Python 2.7(只需更改以下部分内容而不是其他内容)。

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;

请注意,上面的内容是4-space indent convention (PEP 8)。如果您不熟悉Python,我建议您阅读一些教程,以了解缩进的语法和用法。

答案 1 :(得分:0)

您的数据结构错误(是的,缩进很重要......) 无论如何,这里有解决方案:

def get_temp(lat, lon):
    data = urllib2.urlopen(
    "http://api.openweathermap.org/data/2.1/find/station?lat=%s&lon=%s&cnt=1"% (lat, lon))
    js_data = json.load(data)
    try:
        return js_data['list'][0]['main']['temp']
    except (KeyError, IndexError):
        return None

输出:

In [121]: get_temp(50,50)
Out[121]: 275.15