概述
view代码
from rest_framework.views import APIView
from rest_framework.response import Response
class Login(APIView):
'''
登录模块
'''
def post(self,request):
# 获取用户名
name = request.data.get('name')
# 获取密码
password = request.data.get('password')
# 判断参数完整性
if not all([name, password]):
return Response({'msg': '请输入完整的账号密码', 'code': 400})
# 查询是否有该用户
find_user_first = User.objects.filter(name=name).first()
if not find_user_first:
return Response({'msg': '没有找到此用户', 'code': 400})
# 生成token对象
jwt_obj = JwtClass()
# 生成token
token = jwt_obj.create_token(user_number=find_user_first.user_number)
queryset = User.objects.filter(name=name).first()
ser_obj = LoginSer(queryset)
if not token:
return Response({'msg': '生成标识失败', 'code': 400})
return Response({'msg': '登录成功', 'code': 200, 'token': token, 'data': ser_obj.data})
jwt.py代码
# jwt万能类
import jwt
import datetime
from .settings import SECRET_KEY
# from apps.user.models import User
class JwtClass(object):
# 加密token
def create_token(self, user_number):
'''
加密token
:param user_number:
:return:
'''
if user_number:
try:
# 过期时间为一天
token = jwt.encode(
{
'user_number': user_number,
'exp': datetime.datetime.now() + datetime.timedelta(days=1)
},
key=SECRET_KEY, algorithm='HS256'
)
except Exception as err:
print(err)
return None
return token
else:
return None
# 解密token
def check_token(self, token):
'''
解密token
:param token:
:return:
'''
if token:
try:
data = jwt.decode(token, key=SECRET_KEY, algorithms=['HS256'])
user_number = data['user_number']
except Exception as err:
print(err)
print('解密失败')
return None
else:
if User.objects.filter(user_number=user_number):
return user_number
else:
return None
else:
return None
models代码
class User(models.Model):
name = models.CharField(max_length=256, verbose_name='用户名')
password = models.CharField(max_length=256, verbose_name='密码')
serlizer代码
class UserSer(serializers.ModelSerializer):
class Meta:
model = User
fields = "__all__"
最后
以上就是粗心小刺猬为你收集整理的基于jwt模块实现登录功能的全部内容,希望文章能够帮你解决基于jwt模块实现登录功能所遇到的程序开发问题。
如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。
本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
发表评论 取消回复