官方的淘宝SDK是python2,而且调用经常出问题,于是根据算法,自行封装了个。
可以支持大部分API
import time
import urllib
import hashlib
import urllib.parse
import urllib.request
# 这里填写你申请到的APPkey
app_key = 'xxxxxx'
appSecret = 'xxxxxx'
#排序
def ksort(d):
return [(k, d[k]) for k in sorted(d.keys())]
#MD5加密
def md5(s, raw_output=False):
"""Calculates the md5 hash of a given string"""
res = hashlib.md5(s.encode())
if raw_output:
return res.digest()
return res.hexdigest()
#计算sign
def createSign(paramArr):
sign = appSecret
paramArr = ksort(paramArr)
paramArr = dict(paramArr)
for k, v in paramArr.items():
if k != '' and v != '':
sign += k + v
sign += appSecret
sign = md5(sign).upper()
return sign
#参数排序
def createStrParam(paramArr):
strParam = ''
for k, v in paramArr.items():
if k != '' and v != '':
strParam += k + '=' + urllib.parse.quote_plus(v) + '&'
return strParam
#高效API调用示例
def gxapi(item_id, adzone_id, site_id, session):
# 请求参数,根据API文档修改
postparm = {'item_id': item_id,
'adzone_id': adzone_id,
'site_id': site_id,
'session': session,
'method': 'taobao.tbk.privilege.get'
}
# 公共参数,一般不需要修改
paramArr = {'app_key': app_key,
'v': '2.0',
'sign_method': 'md5',
'format': 'json',
'timestamp': time.strftime('%Y-%m-%d %H:%M:%S')
}
paramArr = {**paramArr, **postparm}
sign = createSign(paramArr)
strParam = createStrParam(paramArr)
strParam += 'sign=' + sign
url = 'http://gw.api.taobao.com/router/rest?' + strParam
res = urllib.request.urlopen(url).read()
return res
# mm_17398164_8812194_29632544
if __name__ == '__main__':
res = gxapi('570075443473', '29632544', '8812194', '70000100c0744973c591154b784bb59595d15bc7706a104738d1f13c665d8348dae655b82248874')
print(res)
网友评论