如何从 python 图书馆签署 google 街景请求?

How to sign google street view request from python library?

我正在尝试对 google 地图静态街景 api 进行大量查询。我正在提供我的 Api 密钥,它运行良好,但似乎当它完成一定数量的擦除时,我开始收到 google 返回的禁止错误。经过一番探索后,我确定这是因为我没有使用我的签名密码来签署这些请求。

探索 google 云控制台后,我发现了我的签名秘密,它看起来像这样:

'sadfafKL2-pw43434sPSds2DDk=' #(this is a random string, not actual signing secret)

我现在的困惑集中在如何使用导入 google_streetview.api 包将这个签名秘密传递给我的 google 地图 api 请求参数。我之前使用的当前代码使用 api 密钥但不使用签名密码是:

import google_streetview.api
params = [{
    'size': '640x640',  
    'location':  "34.122342,-118.73721", 
    'key': 'my_key'
}]
results = google_streetview.api.results(params)

如何将我的签名密码添加到此以阻止禁止的错误?

请按照 Google 文档中的说明创建数字签名 https://developers.google.com/maps/documentation/streetview/get-api-key#dig-sig-key

您可以在 Python here 中找到示例代码。

希望对您有所帮助!

Google 在文档 link 中接受的答案中提供的代码示例已过时(Python 2.x?)。 GitHub 他们 link 中的文件自 2016 年以来就没有更新过!我正在为 Python 3. 提交包含更新文件的 PR,但是回购协议已经 2 年多没有更新了,所以谁知道他们是否会查看它。所以这是代码,以防万一:


import hashlib
import hmac
import base64
import urllib.parse as urlparse


def sign_url(input_url=None, secret=None):
    """ Sign a request URL with a URL signing secret.
      Usage:
      from urlsigner import sign_url
      signed_url = sign_url(input_url=my_url, secret=SECRET)
      Args:
      input_url - The URL to sign
      secret    - Your URL signing secret
      Returns:
      The signed request URL
  """

    if not input_url or not secret:
        raise Exception("Both input_url and secret are required")

    url = urlparse.urlparse(input_url)

    # We only need to sign the path+query part of the string
    url_to_sign = url.path + "?" + url.query

    # Decode the private key into its binary format
    # We need to decode the URL-encoded private key
    decoded_key = base64.urlsafe_b64decode(secret)

    # Create a signature using the private key and the URL-encoded
    # string using HMAC SHA1. This signature will be binary.
    signature = hmac.new(decoded_key, str.encode(url_to_sign), hashlib.sha1)

    # Encode the binary signature into base64 for use within a URL
    encoded_signature = base64.urlsafe_b64encode(signature.digest())

    original_url = url.scheme + "://" + url.netloc + url.path + "?" + url.query

    # Return signed URL
    return original_url + "&signature=" + encoded_signature.decode()