Google App Engine: HTTP错误400:错误请求
我正在开发一个应用程序,需要计算用户输入的两个地点之间的距离。为此,我使用了谷歌地图的距离矩阵API。以下是我的代码:
class MainPage(Handler):
def get(self):
self.render('map.html')
def post(self):
addr1 = self.request.get("addr1")
addr2 = self.request.get("addr2")
url = 'http://maps.googleapis.com/maps/api/distancematrix/json?origins=' + addr1 + '&destinations=' + addr2 + '&mode=driving&sensor=false'
link = urllib2.urlopen(url).read()
self.response.write(link)
map.html
<html>
<head>
<title>Fare Calculator</title>
</head>
<body>
<form method = "post">
Source<input type = 'text' name = "addr1">
Destination<input type = 'text' name = "addr2">
<br><br>
<input type = "submit" value = "Calculate Fare">
</form>
</body>
</html>
map.html里有一个简单的HTML表单,用户可以在里面输入起点和终点的地址。不过,当我运行这个应用程序时,出现了HTTP错误400:错误的请求。这是怎么回事呢?
1 个回答
3
你的变量需要进行网址编码,才能用于API请求。
...
url = 'http://maps.googleapis.com/maps/api/distancematrix/json?origins=' + urllib.quote_plus(addr1) + '&destinations=' + urllib.quote_plus(addr2) + '&mode=driving&sensor=false'
...
你可以在这里了解更多关于.quote_plus
的内容。