此地理编码代码在本地运行,但不在服务器中运行,它以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服务器中写这个的正确方法是什么?
答案 0 :(得分: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']
当我使用谷歌驱动器时,这件事发生在我身上,因为很多doucments没有text/html
作为输出格式,我总是得到KeyError
。在您的情况下,您正在处理谷歌地图,如果 结果应该 geometry
和dict中的其他键,但是,您也可以选择将KeyError
添加到您的except子句中,以便更加谨慎。
答案 1 :(得分:1)
您可以使用len()
检查索引是否存在。