这个是百度推广API的一个示例代码,原来是python2的,有没有大神帮我看看为什么46行会报错,谢谢了[Python] 纯文本查看 复制代码 import os
import sys
import urllib
import json
import hashlib
import hmac
import time
import datetime
from urllib.parse import quote
from urllib.parse import urlparse
def gen_auth(access_key, secret_key, utc_time_str, url, method):
url_parse_ret = urlparse(url)
host = url_parse_ret.hostname
path = url_parse_ret.path
version = "1"
expiration_seconds = "1800"
signature_headers = "host"
# 1 Generate SigningKey
val = "bce-auth-v%s/%s/%s/%s" % (version, access_key, utc_time_str, expiration_seconds)
signing_key = hmac.new(secret_key, val, hashlib.sha256).hexdigest().encode('utf-8')
# 2 Generate CanonicalRequest
# 2.1 Genrate CanonicalURI
canonical_uri = quote(path)
# 2.2 Generate CanonicalURI: not used here
# 2.3 Generate CanonicalHeaders: only include host here
canonical_headers = "host:%s" % quote(host).strip()
# 2.4 Generate CanonicalRequest
canonical_request = "%s\n%s\n\n%s" % (method.upper(), canonical_uri, canonical_headers)
# 3 Generate Final Signature
signature = hmac.new(signing_key, canonical_request, hashlib.sha256).hexdigest()
authorization = "bce-auth-v%s/%s/%s/%s/%s/%s" % (version, access_key, utc_time_str, expiration_seconds, signature_headers, signature)
print(authorization)
return authorization
if __name__ == "__main__":
access_key = "AK"
secret_key = "SK"
url = "http://sem.baidubce.com/v1/cloud/PreviewService/getPreview"
method = "POST"
utc_time = datetime.datetime.utcnow()
utc_time_str = utc_time.strftime("%Y-%m-%dT%H:%M:%SZ")
auth = gen_auth(access_key, secret_key, utc_time_str, url, method)
header = {
'accept-encoding':'gzip, deflate',
'host':'sem.baidubce.com',
'content-type':'application/json',
'x-bce-date': utc_time_str,
'authorization': auth,
'accept':'*/*'
}
data = {"header": {"opUsername": "OPUSERNAME", "opPassword": "OPPASSWORD", "tgUsername": "TGUSERNAME", "tgPassword": "TGPASSWORD"},"body": {"keyWords": ["鲜花"],"device": 1, "region":1000}}
data = json.dumps(data)
request = urllib.Request(url, data, header)
response = None
try :
response = urllib.urlopen(request)
post_res_str = response.read()
print(post_res_str)
except urllib2.URLError as e:
print("URLError")
print(e.code, e.reason)
print(e.read())
except urllib2.HTTPError as e:
print("HTTPError")
print(e.code, e.reason)
print(e.read())
|