Google Maps API - 使用Python 3签署地理编码请求

时间:2013-12-19 19:07:09

标签: google-maps-api-3 python-3.x

我尝试创建一个脚本来使用我的Maps API许可证生成已签名的网址以对地址进行地理编码,但我的sign_url功能出现问题。

import urllib
import urllib.parse
import base64
import hashlib
import hmac
import re

google_apis_url_http = 'http://maps.googleapis.com'
geocoding_endpoint_json = '/maps/api/geocode/json'


def encode_params(address, client, sensor):
    return urllib.parse.urlencode({'address': address, 'client': client, 'sensor': sensor})


def sign_url(url, private_key):
    decoded_key = base64.urlsafe_b64decode(private_key)
    signature = hmac.new(decoded_key, url, hashlib.sha1)
    encoded_signature = base64.urlsafe_b64encode(signature.digest())
    return encoded_signature

with open("addresses.txt", "r") as inputFile:
    inputList = inputFile.read().splitlines()

for line_address in inputList[0:1]:
    comma_stripped_address = re.sub(",", "", line_address)
    formatted_address = re.sub(" ", "+", comma_stripped_address)
    encoded_params = encode_params(formatted_address, 'gme-********', 'false')
    url_to_sign = geocoding_endpoint_json + '?' + encoded_params

    print(sign_url(url_to_sign, '********'))

这是我得到的错误:

Traceback (most recent call last):
  File "/Users/[me]/PycharmProjects/Google APIs/geocode_auth.py", line 31, in <module>
    print(sign_url(url_to_sign, '********'))
  File "/Users/[me]/PycharmProjects/Google APIs/geocode_auth.py", line 18, in sign_url
    signature = hmac.new(decoded_key, url, hashlib.sha1)
  File "/Library/Frameworks/Python.framework/Versions/3.3/lib/python3.3/hmac.py", line 131, in new
    return HMAC(key, msg, digestmod)
  File "/Library/Frameworks/Python.framework/Versions/3.3/lib/python3.3/hmac.py", line 73, in __init__
    self.update(msg)
  File "/Library/Frameworks/Python.framework/Versions/3.3/lib/python3.3/hmac.py", line 79, in update
    raise TypeError("expected bytes, but got %r" % type(msg).__name__)
TypeError: expected bytes, but got 'str'

有人知道为什么会引发这个TypeError吗?我是在Python v2中完成的演示中对脚本进行建模,所以它可能会在v3中出现问题......

0 个答案:

没有答案