• django之基于cookie和装饰器实现用户认证


    一、使用Django自带的decorator

    通常情况,使用 函数定义的view,可以直接使用 login_required 直接装饰

    复制代码
    @login_required
    def index(request):
        if request.method == "GET":
            return render(request, "index.htm")
    
    
    def user_login(request):
        if request.method == "GET":
            return render(request, "login.html")
        if request.method == "POST":
            username = request.POST.get("username", "")
            password = request.POST.get("password", "")
            user_obj = authenticate(username=username, password=password)
            if user_obj:
                login(request, user_obj)
                return redirect(request.GET.get("nex", "/"))
            else:
                return render(request, "login.html")
    
    
    def user_logout(request):
        logout(request)
        return render(request, "login.html")
    复制代码

    这里需要注意的是: login_required默认会重定向到 /account/login url, 因此我们可以在Settings.py中修改这个默认的重定向url;

    LOGIN_URL = "/login/"

    但是如果使用类定义的view,是不能够直接使用 login_required进行装饰的

    需要定义一个 LoginRequired类

    复制代码
    from django.contrib.auth.decorators import login_required
    from django.utils.decorators import method_decorator
    
    
    class LoginRequiredMixin(object):
        @method_decorator(login_required(login_url="/login/"))
        def dispatch(self, request, *args, **kwargs):
            return super(LoginRequiredMixin, self).dispatch(request, *args, **kwargs)
    复制代码

    然后在view中进行继承

    xxxView(LoginRequired, View)

      pass

    二、自己写一个认证decorator

    函数装饰器

    复制代码
    # 认证装饰器
    class AuthDecorator(object):
        @method_decorator(login_required(login_url="/login/"))
        def dispatch(self, request, *args, **kwargs):
            return super(AuthDecorator, self).dispatch(request, *args, **kwargs)
    
    
    def has_auth(func):
        def auth(request, *args, **kwargs):
                if not request.session.get("username"):
                    return redirect(reverse("login"))
                return func(request, *args, **kwargs)
        return auth
    
    
    @has_auth
    def index(request):
        user = request.session.get("username")
        business_obj = Business.objects.all()
        user_obj = User.objects.all()
        hosts = Host.objects.filter(user__username=user)
        return render(request, "index.html", {
            "hosts": hosts,
            "business_obj": business_obj,
            "user_obj": user_obj
        })
    复制代码

    类装饰器

    复制代码
    # 认证装饰器
    class Auth(View):
        def dispatch(self, request, *args, **kwargs):
            user_obj = UserInfo.objects.filter(username=request.session.get("username")).first()
            if not user_obj:
                return redirect(reverse("login"))
            return super(Auth, self).dispatch(request, *args, **kwargs)
    
    
    # 主页视图
    class IndexView(Auth):
        def get(self, request):
            user = request.session.get("username")
            business_obj = Business.objects.all()
            user_obj = UserInfo.objects.all()
            hosts = Host.objects.filter(user__username=user)
            return render(request, "index.html", {
                "hosts": hosts,
                "business_obj": business_obj,
                "user_obj": user_obj
            })
    复制代码
     
     
     

    django之基于cookie和装饰器实现用户认证

     

    示例1

    复制代码
     1 # Create your views here.
     2 user = "a"
     3 pwd = "a"
     4 def login(request):
     5     if request.method =="GET":
     6         return render(request,"login.html")
     7     elif request.method == "POST":
     8         u = request.POST.get("user")
     9         p = request.POST.get("password")
    10         print(u)
    11         print(p)
    12         if u ==user and p ==pwd:
    13             res = redirect("/index")
    14             res.set_cookie('user',u,max_age=5)   #设置cookie,关闭浏览器cookie失效。max_age=5表示5秒后cookie失效,需要重新登录
    15             return res
    16         else:
    17             return  render(request,"login.html")
    18 def index(request):
    19     v = request.COOKIES.get("user")
    20     if v:
    21         return render(request,"index.html",{"current_user":v})
    22     else:
    23         return redirect("/login")
    复制代码

    示例2   ---   基于装饰器实现用户认证

    复制代码
     1 user = "a"
     2 pwd = "a"
     3 
     4 def auth(func):
     5     def inner(reqeust,*args,**kwargs):
     6         v = reqeust.COOKIES.get('user')
     7         if not v:
     8             return redirect('/login')
     9         return func(reqeust, *args,**kwargs)
    10     return inner
    11 
    12 def login(request):
    13     if request.method =="GET":
    14         return render(request,"login.html")
    15     elif request.method == "POST":
    16         u = request.POST.get("user")
    17         p = request.POST.get("password")
    18         if u ==user and p ==pwd:
    19             res = redirect("/index")
    20             res.set_cookie('user',u,max_age=5)   #设置cookie,关闭浏览器cookie失效。max_age=5表示5秒后cookie失效,需要重新登录
    21             return res
    22         else:
    23             return  render(request,"login.html")
    24 @auth
    25 def index(request):
    26     v = request.COOKIES.get("user")
    27     return render(request,"index.html",{"current_user":v})
    复制代码
  • 相关阅读:
    Problem C: 类的初体验(V)
    接口与继承
    类和对象
    java函数方法
    数组
    string类的一些函数方法
    java语法基础
    大道至简——做个懒人
    java编程 求和
    编程的精义
  • 原文地址:https://www.cnblogs.com/xc1234/p/8594570.html
Copyright © 2020-2023  润新知