Python 登录接口token生成

603次阅读

登录接口中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次一致的时间戳)
Python

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对象

Python

 

 

yiywain
版权声明:本文于2021-07-28转载自Python 登录接口token生成,共计2260字。
转载提示:此文章非本站原创文章,若需转载请联系原作者获得转载授权。