我正在开发一个应用程序,该应用程序需要计算用户输入的两个位置之间的距离。我正在使用 Google map 的距离矩阵 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:错误请求。发生什么事了?
最佳答案
您的变量需要针对 API 请求进行 urlencode 编码。
...
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
here 的更多信息。 .
关于python - 谷歌应用引擎: HTTP Error 400: Bad Request,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22338060/