python - 谷歌应用引擎: HTTP Error 400: Bad Request

标签 python google-maps google-app-engine google-maps-api-3

我正在开发一个应用程序,该应用程序需要计算用户输入的两个位置之间的距离。我正在使用 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">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
        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/

相关文章:

python - 使用 SSL 公钥/私钥在 Windows 上为女服务员提供 Flask 应用程序

Python Pandas - Groupby 并制作列值标题

python - 计算不同长度数组的平均值

javascript - 带有 document.getElementById 的 Reactjs 样式组件

Android 数组列表如何使用

python - 如何防止keras重命名图层

javascript - 如何在没有外部库的情况下监听 Google Maps API 事件?

google-app-engine - 在 Go 中设置 App Engine 上下文

java - 以编程方式创建任务队列

java - 使用 Objectify 查询 Geopt