【问题标题】:How to sign google street view request from python library?如何从 python 库签署谷歌街景请求?
【发布时间】:2019-07-02 04:58:06
【问题描述】:

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

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

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

我现在的困惑集中在如何使用 import google_streetview.api 包将此签名秘密传递给我的 google maps api 请求参数。我之前使用的当前代码采用 apikey 但不采用签名密钥:

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

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

【问题讨论】:

    标签: python google-maps google-street-view


    【解决方案1】:

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

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

    希望这会有所帮助!

    【讨论】:

      【解决方案2】:

      Google 在已接受答案中链接的文档中提供的代码示例已过时(Python 2.x?)。他们链接到的 GitHub 中的文件自 2016 年以来就没有更新过!我正在提交一个带有 Python 3 更新文件的 PR,但是该 repo 已经超过 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()
      

      【讨论】:

      • 我的拉取请求已被接受,因此官方 GitHub 存储库中的 Python 代码示例现已更新为 Python 3
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-03-30
      • 1970-01-01
      • 2010-09-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多