Python 登錄接口token生成

Python 登錄接口token生成

登錄接口中token一般都是MD5加密規則生成的,MD5加密規則請參照開發給的接口技術文檔;
token加密規則如下:

//先從接口對接負責人處拿到 【 API_SECRET 】 => 接口密鑰(一個含有數字、大小寫字母的隨機字符串)
define("API_SECRET","隨機字符串");
$project_code = "GET傳遞的項目編碼";
$account = "GET傳遞的登錄帳號";
$time_stamp = "GET傳遞的時間戳";
$token = md5( $project_code + $account + $time_stamp + API_SECRET );
構造函數的方法

1、獲取當前時間戳:

import time
#獲取時間戳
def t_stamp():
    t = time.time()
    t_stamp = int(t)
    print('當前時間戳:', t_stamp)
    return t_stamp

2、生成token:

import hashlib
#token加密
def token():
    API_SECRET = "xxxx" #從接口對接負責人處拿到
    project_code = "xxxx"  #GET傳遞的項目編碼,參數值請根據需要自行定義
    account = "xxxx"   #GET傳遞的登錄帳號,參數值請根據需要自行定義
    time_stamp =str(t_stamp())  #int型的時間戳必須轉化爲str型,否則運行時會報錯
    hl = hashlib.md5()  # 創建md5對象,由於MD5模塊在python3中被移除,在python3中使用hashlib模塊進行md5操作
    strs = project_code + account + time_stamp + API_SECRET # 根據token加密規則,生成待加密信息
    hl.update(strs.encode("utf8"))  # 此處必須聲明encode, 若爲hl.update(str)  報錯爲: Unicode-objects must be encoded before hashing
    token=hl.hexdigest()  #獲取十六進制數據字符串值
    print('MD5加密前爲 :', strs)
    print('MD5加密後爲 :', token)
    return token  
創建類的方法

1、獲取當前時間戳:

import time
#獲取時間戳
class Time(object):
    def t_stamp(self):
        t = time.time()
        t_stamp = int(t)
        print('當前時間戳:', t_stamp) #在class 類裏打印數據,然後再調用N次該類時,會打印出N次一致的時間戳;如圖所訴:建議不要在類裏打印數據;
        return t_stamp

運行結果如圖所訴:(類裏打印數據,然後再調用N次該類時,會打印出N次一致的時間戳)
在這裏插入圖片描述

2、生成token:

import hashlib
import time
import json
# 創建獲取token的對象
class Token(object):
    def __init__(self, api_secret, project_code, account):
        self._API_SECRET = api_secret
        self.project_code = project_code
        self.account = account
    def get_token(self):
        strs = self.project_code + self.account + str(Time().t_stamp()) + self._API_SECRET
        hl = hashlib.md5()
        hl.update(strs.encode("utf8"))  # 指定編碼格式,否則會報錯
        token = hl.hexdigest()
        print('MD5加密前爲 :', strs)
        print('MD5加密後爲 :', token)
        return token

3、全部代碼如下:

import hashlib
import time
import requests
import json
# 創建獲取時間戳的對象
class Time(object):
    def t_stamp(self):
        t = time.time()
        t_stamp = int(t)
        print('當前時間戳:', t_stamp)
        return t_stamp

# 創建獲取token的對象
class Token(object):
    def __init__(self, api_secret, project_code, account):
        self._API_SECRET = api_secret
        self.project_code = project_code
        self.account = account
    def get_token(self):
        strs = self.project_code + self.account + str(Time().t_stamp()) + self._API_SECRET
        hl = hashlib.md5()
        hl.update(strs.encode("utf8"))  # 指定編碼格式,否則會報錯
        token = hl.hexdigest()
        #print('MD5加密前爲 :', strs)
        print('MD5加密後爲 :', token)
        return token

if __name__ == '__main__':
    tokenprogramer = Token('api_secret具體值', 'project_code具體值', 'account具體值')  # 對象實例化
    tokenprogramer.get_token()   #調用token對象

運行結果如下:
在這裏插入圖片描述

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章