def create_salt(length): salt = '' chars = 'AaBbCcDdEeFfGgHhIiJjKkLlMmNnOoPpQqRrSsTtUuVvWwXxYyZz0123456789!@#$%&*^()-+=[]{}|_`~?/,.<>;:' len_chars = len(chars) - 1 for i in range(length): # 每次从chars中随机取一位 salt += chars[random.randint(0, len_chars)] return salt salt = create_salt(8) def flat(prefix, obj): l = [] if type(obj) == dict: if obj: for k, v in obj.items(): l = l + flat(prefix + '.' + k if len(prefix) else k, v) else: l = [prefix + '=' + str(obj)] elif type(obj) == list: if obj: for i, v in enumerate(obj): l = l + flat(prefix + '[' + str(i) + ']', v) else: l = [prefix + '=' + str(obj)] elif type(obj) == float: obj = '{:.11e}'.format(obj).replace('e+0', 'E') l = [prefix + '=' + str(obj)] elif obj is None: pass elif obj is True: l = [prefix + '=true'] elif obj is False: l = [prefix + '=false'] else: l = [prefix + '=' + str(obj)] return l def sign(obj): # 如果有signature字段,删除掉,签名不包含signature字段 if "signature" in obj.keys(): del obj["signature"] # 注意设置对应的senderKey s = '&'.join(sorted(flat('', obj) + ['senderKey=123456789'])) return hashlib.sha256(s.encode('utf-8')).hexdigest() def create_body(request_body,sender="xxxxxx"): # request_body = json.loads(request_body) request_body['requestId'] = requestId request_body['locale'] = "en_KE" request_body['sender'] = sender request_body['salt'] = salt request_body['timestamp'] = timestamp signature = sign(request_body) request_body['signature'] = signature request_body = json.dumps(request_body) return request_body
示例
request_body = { "params": { "key1": "xxxxxx", "key2": "ddddddd" }, "signature": "" } url= "http://xxxxxxxxx.com" a=create_body(request_body) body=json.loads(a) print(body)
r2=requests.post(url=url, json=body, verify= False) print(r2.content.decode())