Google 地图地理定位 API 在 Web 服务器上调用 returns invalidRequest 但不是在本地

Google Maps Geolocate API call returns invalidRequest on web server but not locally

我有一个 Django 站点,当 运行 在我本地计算机上的 Django 开发服务器上时,它可以正常工作。当我尝试 运行 我的 pythonanywhere account, everything works except for a single call to the Google Maps Geolocation API.

网站时

失败的函数调用是:

def geolocate():
    url = "https://www.googleapis.com/geolocation/v1/geolocate?key=%s" % API_KEY
    r = requests.post(url)
    lat_lng = r.json()['location']
    return (lat_lng['lat'], lat_lng['lng'])

当在 pythonanywhere 上 运行 时,我从 requests.post() 调用返回的响应是:

{
"error": {
  "errors": [
   {
    "domain": "geolocation",
    "reason": "invalidRequest",
    "message": "Bad Request"
   }
  ],
  "code": 400,
  "message": "Bad Request"
 }
}

而当我在开发服务器上 运行 它时,我得到:

{
 "location": {
  "lat": 39.9546734,
  "lng": -96.5985613
 },
 "accuracy": 2678.0
}

这是我正在寻找的回复。

我还尝试在我的本地机器上和从 pythonanywhere bash 控制台上使用 curl 发出请求。使用此命令:

curl 'https://www.googleapis.com/geolocation/v1/geolocate?key=MY_API_KEY' -H "Content-Type: application/json" -d {}

我从 pythonanywhere 得到了相同的 400 响应,但在我的本地机器上得到了预期的位置数据。 .googleapis.com 是 pythonanywhere 的白名单域之一,我在 pythonanywhere 上的 Django 站点调用 Google Maps Geocode and Places APIs in JavaScript 并调用网络服务没有任何问题。这似乎只是 Geolocate API.

的问题

另一条可能有用的信息:当我将 -v 标志与 curl 一起使用以获得更详细的输出时,我发现当我在 pythonanywhere 上发出“错误请求”时,我得到该行:

* Server GSE is not blacklisted

当我在本地 运行 命令时我没有看到。我进行了一些搜索,但无法弄清楚这意味着什么或是否相关,但它很突出,所以我想我会提一下,以防它为更多知识渊博的用户举起旗帜。

我已经看到 this question, and this question,以及一些看似相关但未解决的错误报告,但我也想 post 我的问题,因为我的问题似乎与我发现的任何现有问题。任何帮助,将不胜感激。谢谢!

更新:

我在 DigitalOcean droplet 上做了一些实验,发现当地理定位请求成功 returns 位置信息时 运行 在 droplet 上,它给了我纬度和经度纽约市的一个地址(液滴位于我知道位于纽约市的服务器上)。不幸的是,由于我正在尝试对用户进行地理定位,因此此信息甚至不如错误消息有用...

我仍然不知道为什么请求在 pythonanywhere 上失败但在 DigitalOcean 上成功(除了可能,正如@Glenn 所建议的那样,Goggle 在一种情况下知道它甚至不应该费心检索位置信息),但我想这与我的问题不再相关,因为即使它在 pythonanywhere 上成功了,它也会给我无用的——或者更糟的,误导性的——信息。我想我得想出另一种方法来获取用户位置。

向 google 地理定位发送一个空的请求正文相当于 "tell me where this machine is"。我认为 Google 足够聪明,知道尝试获取 AWS 实例的位置是没有意义的。