求助python大神看个代码
这个是百度推广API的一个示例代码,原来是python2的,有没有大神帮我看看为什么46行会报错,谢谢了import osimport 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())
AK,SK都要换成你自己的 3楼正解。。。 人家示例代码内容都没填 建议再贴一张报错的图 广州最 发表于 2019-8-8 14:39
建议再贴一张报错的图
报错信息:TypeError: key: expected bytes or bytearray, but got 'str'
主要是gen_auth函数里面不知道哪里的问题,这个代码本来是python2的,python3可能是什么地方需要改才行。 离人心上秋意浓 发表于 2019-8-8 14:33
3楼正解。。。 人家示例代码内容都没填
NONONO,还没到一步就已经报错了 URL我这里访问不了 wanwfy 发表于 2019-8-8 14:46
报错信息:
主要是gen_auth函数里面不知道哪里的问题,这个代码本来是python2的,python3可能是什么地 ...
46行的参数必须是字节或者字节素组,不能是字符串 小屎球 发表于 2019-8-8 14:53
URL我这里访问不了
你必须访问不了啊,还要加参数 wanwfy 发表于 2019-8-8 15:03
你必须访问不了啊,还要加参数
我是说 ping这个域名都没解析出IP
页:
[1]
2