美文网首页
Day6-课堂笔记-Django6

Day6-课堂笔记-Django6

作者: 晓晓的忍儿 | 来源:发表于2018-09-17 19:34 被阅读0次

    1.自定义登录

    1)创建user表

    user->models.py

    class Users(models.Model):
        username=models.CharField(max_length=10,unique=True,verbose_name='用户名')
        password=models.CharField(max_length=255,verbose_name='密码')
        create_time=models.DateTimeField(auto_now_add=True,verbose_name='创建时间')
        operate_time=models.DateTimeField(auto_now=True,verbose_name='修改时间')
    
        class Meta:
            db_table='users'
    

    2)用户注册代码

    def register(request):
        if request.method=='GET':
            # 如果请求为get,返回注册页面
            return render(request,'register.html')
        if request.method=='POST':
            #校验参数
            form=UserForm(request.POST)
            # 判断是否校验成功,is_valid()为true校验成功
            if form.is_valid():
                # 注册,使用make_password进行密码加密,否则为明文
                password=make_password(form.cleaned_data['password1'])
                Users.objects.create(username=form.cleaned_data['username'],
                                     password=password)
                # 跳转到登录页面,使用namespace:name
                return HttpResponseRedirect(reverse('user:login'))
            else:
                return render(request,'register.html',{'form':form})
    

    2.设置装饰器

    1)创建user_ticket表

    class UserTicket(models.Model):
        #
        user=models.ForeignKey(Users)
        ticket=models.CharField(max_length=30)
        create_time=models.DateTimeField(auto_now_add=True,verbose_name='创建时间')
        max_age=models.DateTimeField(auto_now=True,verbose_name='修改时间')
        class Meta:
            db_table='user_ticket'
    

    2)登录:

    def login(request):
        if request.method=='GET':
            return render(request,'login.html')
        if request.method=='POST':
            # 校验登录页面传递的参数
            form=LoginForm(request.POST)
            # 使用is_valid()判断是否校验成功
            if form.is_valid():
                # 登录的设置
                # 1.通过用户名和密码获取当前的user对象-->类似authenticate
                user=Users.objects.filter(username=form.cleaned_data['username']).first()
                if user:
                    # 可以通过username获取到对象
                    # 将user.password和from.form.cleaned_data['password']进行校验
                    if check_password(form.cleaned_data['password'],user.password):
                        # 校验用户名和密码都成功
                        #1.向cookie中设置随机参数ticket
                        res = HttpResponseRedirect(reverse('user:index'))
                        ticket=get_ticekt()
                        # set_cookie(key,value,max_age'',expires=''),key键,value值,max_age存活时间-s,expires-天
                        # 设置cookie中的随机值-->类似auth.login
                        res.set_cookie('ticket',ticket,max_age=100)
                        # 删除cookie,delete_cookie(key)
                        # delete_cookie('ticket')
                        # 2.在表user_ticket中设置这个ticket和user的对象关系
                        # 设置user_ticket中ticket的随机值
                        UserTicket.objects.create(user=user,ticket=ticket)
                        return res
                    else:
                        # 密码错误
                        return render(request,'login.html',{'password':'密码错误'})
                else:
                    # 登录系统的用户不存在
                    return render(request,'login.html',{'username':'用户不存在'})
                pass
            else:
                return render(request,'login.html',{'form':form})
    

    3)登录跳转首页验证(装饰器)

    方法一:
    得到随机ticket
    utils->functions->get_ticekt

    def get_ticekt():
        s='1234567890qwertyuiopasdfghjklzxcvbnm'
        ticket=''
        for i in range(25):
            ticket+=random.choice(s)
        return ticket
    

    user->views

    def index(request):
        if request.method=='GET':
            # 从cookie中拿ticket
            ticket=request.COOKIES.get('ticket')
            user_ticket=UserTicket.objects.filter(ticket=ticket).first()
            if user_ticket:
                #获取当前登录系统的用户
                user=user_ticket.user
                return render(request,'index.html',{'user':user})
            else:
                return HttpResponseRedirect(reverse('user:login'))
            
    

    方法二:
    创建装饰器:

    # func是一个函数,该函数是在装饰器下面的函数
    def is_login(func):
        def check(request):
            ticket=request.COOKIES.get('ticket')
            # 如果cookie中存在设置的ticket则通过user_ticket表进行校验
            if ticket:
                user_ticket=UserTicket.objects.filter(ticket=ticket).first()
                if user_ticket:
                    return func(request)
                else:
                    # ticket参数错误,则跳转到登录
                    return HttpResponseRedirect(reverse('user:login'))
            else:
                # 没有登录
                return HttpResponseRedirect(reverse('user:login'))
        return check
    
    

    方法三:
    djg6->settings->MIDDLEWARE:末尾添加

    'utils.UserAuthMiddleWare.UserMiddleware',
    

    utils中创建UserAuthMiddleWare.py

    from datetime import datetime
    
    from django.http import HttpResponseRedirect
    from django.urls import reverse
    from django.utils.deprecation import MiddlewareMixin
    
    from user.models import UserTicket
    
    
    class UserMiddleware(MiddlewareMixin):
        # 重构拦截请求的方法
        def process_request(self,request):
            # 排除不需要登录验证的地址
            not_login_path=['/user/login/','/user/register/']
            path=request.path
            # 校验不需要登录验证的地址
            for n_path in not_login_path:
                # 如果当前访问的地址是登录或注册地址,则直接访问对应的视图函数
                if path==n_path:
                    return None
            # ticket=request.COOKIES.get('ticket')
            ticket=request.COOKIES.get('ticket')
            # 如果请求的cookie中没有ticket,则跳转到登录
            if not ticket:
                return HttpResponseRedirect(reverse('user:login'))
    
            # 删除user_ticket表中,时间超过了1000s的记录
            user_tickets = UserTicket.objects.all()
            user_tickets.update(max_age=datetime.now())
            for user in user_tickets:
                times = datetime.timestamp(user.create_time) + 1000000 - datetime.timestamp(user.max_age)
                if times < 0:
                    user.delete()
    
            # 如果请求的user_ticket中没有与cookie中相等的ticket,则跳转到登录
            user_ticket=UserTicket.objects.filter(ticket=ticket).first()
            if not user_ticket:
                return HttpResponseRedirect(reverse('user:login'))
            # 设置全局的user
            request.user=user_ticket.user
            # 返回中间件执行结束,可返回None或可不写
            return None
    

    4)删除ticket

    utils->UserAuthMiddleWare.py

    # 删除user_ticket表中,时间超过了1000s的记录
            user_tickets = UserTicket.objects.all()
            user_tickets.update(max_age=datetime.now())
            for user in user_tickets:
                times = datetime.timestamp(user.create_time) +8*60*60+100 - datetime.timestamp(user.max_age)
                if times < 0:
                    user.delete()
    

    5)注销

    方法一:
    views

    def logout(request):
        if request.method=='GET':
            # 注销写法
            ticket=request.COOKIES.get('ticket')
            user_ticket=UserTicket.objects.filter(ticket=ticket).first()
            if user_ticket:
                user_ticket.delete()
            return HttpResponseRedirect(reverse('user:login'))
    

    方法二:
    utils->functions.py->is_logout:

    def is_logout(func):
        def check(request):
            ticket = request.COOKIES.get('ticket')
            if ticket:
                user_ticket = UserTicket.objects.filter(ticket=ticket).first()
                if user_ticket:
                    user_ticket.delete()
                    return func(request)
                else:
                    return HttpResponseRedirect(reverse('user:login'))
            else:
                return HttpResponseRedirect(reverse('user:login'))
        return check
    

    相关文章

      网友评论

          本文标题:Day6-课堂笔记-Django6

          本文链接:https://www.haomeiwen.com/subject/twhknftx.html