django做接口需要对重要信息进行加密和解密。
# 需要安装pip install itsdangerous
from itsdangerous import TimedJSONWebSignatureSerializer as Serializer
# 自己设置的秘钥
secret_key = 'ihdskjghksdf4356fd'
expires_in = None #如果是None默认3600,可以自己设置时间,单位(s),eg:3600
class SecretOauth(object):
def __init__(self):
self.serializer = Serializer(secret_key=secret_key, expires_in=expires_in)
# 加密
def dumps(self, content_dict):
token = self.serializer.dumps(content_dict).decode()
return token
# 解密
def loads(self, token):
try:
content_dict = self.serializer.loads(token)
except Exception as e:
print(e)
return None
return content_dict
if __name__ == '__main__':
res = SecretOauth().dumps(content_dict={'session_key': 'kdshgjkhskjd8', 'openid': 'hdskghkj884j'})
print('加密后:', res)
import time
time.sleep(2)
res2 = SecretOauth().loads(res)
print('解密后:', res2)
print(res2.get('session_key'))
print(res2['session_key'])
源码说明的expires_in: