• 接口请求加签名


    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())
  • 相关阅读:
    拒绝拖延症
    Spring 九大事务失效场景分析
    蜂鸟E203学习笔记(四)——取指
    SDN落地场景
    【Excel VBA和Python对照学习】创建嵌入式图表
    程序员为讨好老婆,用go写了如下程序,细思极恐
    数据库课后习题加真题
    [深度学习] python基础支持汇总
    实现Runnable接口
    js实现的模拟弹性网格布拉扯仿真动画可拉伸可切割
  • 原文地址:https://blog.csdn.net/u010244522/article/details/127919088