0

此地理编码代码在本地工作,但不在服务器中工作,它以 的形式获取地址并从函数self.request.get('address')返回值。ndb.GeoPt()get_lat_long(address)

那么,我怎么会得到错误:

Traceback (most recent call last):
  File "/base/data/home/runtimes/python27/python27_lib/versions/third_party/webapp2-2.5.2/webapp2.py", line 1535, in __call__
    rv = self.handle_exception(request, response, e)
  File "/base/data/home/runtimes/python27/python27_lib/versions/third_party/webapp2-2.5.2/webapp2.py", line 1529, in __call__
    rv = self.router.dispatch(request, response)
  File "/base/data/home/runtimes/python27/python27_lib/versions/third_party/webapp2-2.5.2/webapp2.py", line 1278, in default_dispatcher
    return route.handler_adapter(request, response)
  File "/base/data/home/runtimes/python27/python27_lib/versions/third_party/webapp2-2.5.2/webapp2.py", line 1102, in __call__
    return handler.dispatch()
  File "/base/data/home/runtimes/python27/python27_lib/versions/third_party/webapp2-2.5.2/webapp2.py", line 572, in dispatch
    return self.handle_exception(e, self.app.debug)
  File "/base/data/home/runtimes/python27/python27_lib/versions/third_party/webapp2-2.5.2/webapp2.py", line 570, in dispatch
    return method(*args, **kwargs)
  File "/base/data/home/apps/s~map-jobs/2.371278632227250958/main.py", line 453, in post
    profile.geopoint = get_lat_long(self.request.get('address'))
  File "/base/data/home/apps/s~map-jobs/2.371278632227250958/main.py", line 17, in get_lat_long
    lat = data['results'][0]['geometry']['location']['lat']
IndexError: list index out of range

使用此代码:

def get_lat_long(address):
  address = cgi.escape(address.replace(" ","+"))
  sensor = "true"
  url = "http://maps.googleapis.com/maps/api/geocode/json?address=" + address + "&sensor="+ sensor
  result = urlfetch.fetch(url)
  data = json.loads(result.content)
  lat = data['results'][0]['geometry']['location']['lat']
  long = data['results'][0]['geometry']['location']['lng']
  return ndb.GeoPt(str(lat) +","+ str(long))

在 google-app-engine 服务器中写这个的正确方法是什么?

4

2 回答 2

1

data['results'][0]实际上是空的。

当没有结果时会发生这种情况。通常,我只是把它放在一个try/catch块中,除了IndexError

try:
    data['results'][0]....
except IndexError, e:
    print "No data found"  # You can use a logger here too

在您的情况下,请在以下代码周围放置一个try/catch块,并找到处理错误的方法:

  lat = data['results'][0]['geometry']['location']['lat']
  long = data['results'][0]['geometry']['location']['lng']

这发生在我身上很多,当我使用谷歌驱动器时,由于很多文档没有text/html作为输出格式,我总是得到KeyError. 在您的情况下,您正在处理谷歌地图,并且如果有结果应该geometry并且字典中的其他键,但是,您也可以选择添加KeyError到您的 except 子句以格外小心。

于 2013-10-30T09:20:43.337 回答
1

您可以使用len()来检查索引是否存在。

于 2013-10-30T10:21:57.030 回答