登录注册注销
如果需要给表设置权限,没有登录就不可以查看,只需要在每个视图函数之前加上Auth_classes=[ ]即可!
增加两张表,做登录认证 #models.py #做登录验证 class Users(models.Model): user=models.CharField(max_length=32) pwd=models.CharField(max_length=32) type=((1,"VIP"),(2,"SVIP"),(3,"SSVIP")) user_type=models.IntegerField(choices=type) class Usertoken(models.Model): token=models.CharField(max_length=128) user=models.OneToOneField("Users")
url("login", LoginView.as_view()),
#app01/view/login.py from rest_framework.views import APIView from ..models import * from ..utils.response import BaseResponse from rest_framework.response import Response class LoginView(APIView): """ 1000:成功 1001:用户名或者密码错误 1002:异常错误 """ def post(self, request): response=BaseResponse() #重写了这个装填码的类 try: print(request.data) user = request.data.get("user") pwd = request.data.get("pwd") user = Users.objects.filter(user=user, pwd=pwd).first() import uuid random_str = uuid.uuid4() if user: Usertoken.objects.update_or_create(user=user, defaults={"token": random_str}) response.user = user.user response.token= random_str else: response.code= 1001 response.msg= "用户名或者密码错误" except Exception as e: response.code = 1002 response.msg= str(e) return Response(response)
#app01/utils/response.py class BaseResponse(object): def __init__(self,): self.code=1000 self.data="" self.error="" @property def dict(self): return self.__dict__ if __name__ == '__main__': response=BaseResponse() response.xxx=123 print(response.dict)
结合VUE即可做登录验证
设置session
为什么设置session? 由于在做好了登录页面之后发现,刷新之后就会回到登录之前的页面,所以需要给登录的用户在浏览器上存储状态,需要设置session,
里边放上username和token,这样刷新页面就会将用户登录状态保存一端时间。设置session的方法: 在django中设置session 设置cookie:response.set_cookie("k1","v3",20) #表示登录状态为20min 获取cookie:request.cookie{"k1":"v3"} 设置session:request.session["k2"]="v4" 获取session:request.session.get("k2") 在vue中设置cookie 设置cookie:COOKIE.set("k1","v1",20min) 获取cookie:COOKIE.get("") 清除cookie:COOKIE.REMOVE("K1")
账户注销--使用vue
也就是将,cookie中的username,usertoken设置为空
具体操作: