itsdangerous 官网中有介绍它的一段话
‘Sometimes you just want to send some data to untrusted environments. But how to do this safely? The trick involves signing. Given a key only you know, you can cryptographically sign your data and hand it over to someone else. When you get the data back you can easily ensure that nobody tampered with it.’
翻译如下:
有时您只想将一些数据发送到不受信任的环境。但如何安全地做到这一点呢?诀窍在于签约。只给你知道的一把钥匙,你就可以用密码签署你的数据,然后把它交给别人。当你取回数据时,你可以很容易地确保没有人篡改它。
它有很多使用方法:参考 官网地址:‘https://pythonhosted.org/itsdangerous/’
下面写了一个简单的小例子 关于忘记密码
from itsdangerous import TimedJSONWebSignatureSerializer as TJW
from django.conf import settings
class FogetPwdView1(APIView):
def get(self,request,*args,**kwargs):
name = request.GET.get('name')
# 判断手机号是否存在
user = models.User.objects.filter(username=name)
# 使用反向关联查询 返回的是查询集
obj_set = user.first().sports.all()
for obj in obj_set:
print(obj.name,obj.id)
if not user:
return Response({'info':'用户名不存在请重新输入!','code':400})
# 生成access_token
tjw = TJW(settings.SECRET_KEY,300)
data = {
'mobile':user.first().mobile,
'username':name
}
# 携带数据
token = tjw.dumps(data)
datas = {'token':token}
return Response(datas)
class FogetPwdView2(APIView):
def get(self,request,*args,**kwargs):
mobile = request.GET.get('mobile')
token = request.GET.get('token')
password = request.GET.get('pwd')
# 判断手机号是否存在
user = models.User.objects.get(mobile=mobile)
if not user:
return Response({'info':'手机号不存在请重新输入!','code':400})
# itsdangerous 令牌
tjw = TJW(settings.SECRET_KEY,300)
# 解析token 数据
data = tjw.loads(token)
if data['mobile'] != mobile:
return Response({'info':'您输入的手机号与系统中登记时的手机号不一致,请确认后重新输入!','code':400})
user.set_password(password)
user.save()
return Response({'msg':'密码重置成功!','code':200})
测试:第一步生产access_token