python dictionary and json.dumps () analysis of pit encountered

Recent projects need to do docking tube Yi Yun erp, saw his interface documentation, sample code, php, so in python parodies.

Wherein the parameter data passed in the first few json data are fixed, and finally need to add a signature that is after the preceding data string of json, the end to end splicing screct string, do md5 treatment (upper case 32) json parameter passed in the past as a post before, and then added to the signature.

When the problem lies in the assembly json string and signature, because python built-in dictionary is unordered, led me to the assembled json data is passed to the function I have written signature as an argument, the order of the internal dictionary is changing, so the signature md5 values ​​before and after are not the same, leading to frequent error that he initially did not care about the data sequence to do, because this one is not signed, the data transfer is simple docking Kingdee erp, resulting in the wrong direction occurs when troubleshooting. Then think of the care begun to address this.

The solution is to use collections library OrderedDict (ordered dictionary) module, the assembled data is not out of order, do the md5 signature also consistent

However, when data for use json json.dumps () method, a string of data will be in a space after the comma, resulting in an error value md5

principle:

file

The solution is

json.dumps(data,separators=(',',':'))

Finally, write their own functions left to be an example

def getShops(): data = OrderedDict() data["appkey"] = appkey data["sessionkey"] = sessionkey data["method"] = method data["page_no"] = "1" data["page_size"] = "10" data["sign"] = sign(data,secret) response = requests.post(url=url, data=json.dumps(data)) print(response.text)

def sign(data,secret): str = json.dumps(data,separators=(',',':')) fullStr = secret+str+secret signCode = hashlib.md5(fullStr.encode("utf-8")).hexdigest().upper() #print(signCode) return signCode

Published 38 original articles · won praise 1 · views 2191

Guess you like

Origin blog.csdn.net/wulishinian/article/details/104836443