s11 day103 luffy项目结算部分+认证+django-redis

1.增加认证用的表

class Account(models.Model):
    username =models.CharField("用户名",max_length=64,unique=True)
    email= models.EmailField(
        verbose_name="邮箱",
        max_length=255,
        unique=True,
        blank=True,
        null=True,
    )
    password =models.CharField("密码",max_length=128)

class UserToken(models.Model):
    user =models.OneToOneField(to ="Account")
    token =models.CharField(max_length=36)
    
python3 manage.py makemigrations

python3 manage.py migrate
 
数据迁移

2. 添加auth认证模块

url

    url(r"^auth/$",auth.AuthView.as_view({"post":"login"})),

views auth

import uuid
from api import models
from rest_framework.response import Response
from rest_framework.viewsets import ViewSetMixin
from rest_framework.views import APIView
from api.utils.response import BaseResponse
class AuthView(ViewSetMixin,APIView):
    def login(self,request,*args,**kwargs):
        #用户登录认证
        response =BaseResponse()   #构建一个字典作为异常处理
        try:
            user=request.data.get("username")
            pwd =request.data.get("password")
            obj = models.Account.objects.filter(username =user,password=pwd).first()
            if not obj:
                print(obj.username)
                response.code =10002
                response.error="用户名或密码错误"
            else:
                print(obj.password)
                uid =str(uuid.uuid4())
                models.UserToken.objects.update_or_create(user=obj,defaults={"token":uid})
                response.code =9999
                response.data =uid
        except Exception as e:
            response.code= 10005
            response.error ="操作异常"
        return Response(response.dict)
class BaseResponse(object):

    def __int__(self):
        self.code = 1000
        self.data = None
        self.error =None

    @property
    def dict(self):
        return self.__dict__

验证

 

  

猜你喜欢

转载自www.cnblogs.com/mengbin0546/p/9473865.html
今日推荐