• Django学习笔记第八篇--实战练习四--为你的视图函数自定义装饰器


    零、背景:

    对于登录后面所有视图函数,都需要验证登录信息,一般而言就是验证cookie里面的一些信息。所以你可以这么写函数:

    1 def personinfo(request):
    2     if request.COOKIES.get("login_flag") == "1":
    3         return HttpResponse("Success!")
    4     else:
    5         return HttpResponse("Failed!")

    这样就可以验证登录与否然后对应返回了。但是有没有觉得每个视图函数都这么写,类似了。那么我们可以自定义装饰器。

    一、装饰器的写法:

    logincheck/logincheck.py

     1 from django.http import HttpResponseRedirect
     2 def login_need(func):
     3     def in_func(request):
     4         if request.COOKIES.get("login_name") not in ["",None," "]:
     5             if request.COOKIES.get("login_flag") == "1":
     6                 return func(request)
     7             else:
     8                 print request.COOKIES
     9                 return HttpResponseRedirect("/myapp1/login")
    10         else:
    11             print request.COOKIES
    12             return HttpResponseRedirect("/myapp1/login")
    13     return in_func

    然后在myapp1/views.py中使用

    1 @logincheck.login_need
    2 def main(request):
    3     return render(request,"welcome.html")

    就可以了,后面的视图都是这么写会省很多事情。

    二、突然发现我这个视图这么写,会导致一个问题越权:

    [01/Feb/2018 17:08:54]"GET /myapp1/mainpage?name=chenran HTTP/1.1" 301 0
    [01/Feb/2018 17:08:54]"GET /myapp1/mainpage/?name=chenran HTTP/1.1" 200 130
    [01/Feb/2018 17:09:06]"GET /myapp1/mainpage/?name=chenran01 HTTP/1.1" 200 130
    [01/Feb/2018 17:09:13]"GET /myapp1/mainpage/?name=chenranxss HTTP/1.1" 200 130

    可想而知,我登录的时候都是一个账号,我返回的信息是确实跟随着那么参数走的,这样是有问题的。

    视图函数应该这么写才对:

    1 @logincheck.login_need
    2 def main(request):
    3     if request.COOKIES["login_name"] == request.GET["name"]:
    4         return render(request,"welcome.html")
    5     else:
    6         return render(request,"error.html")

    这次没想到自己还写了个越权,真的是一步不小心都不行。

  • 相关阅读:
    语句
    C#语言基础
    进制转换
    js对URL的相关操作集锦
    js/javascript计时器方法及使用场景
    js中FormData+XMLHttpRequest数据传输
    HTML中footer固定在页面底部的若干种方法
    js/jquery 禁用点击事件
    asp.net微信开发第七篇----高级群发(图文)
    asp.net微信开发第六篇----高级群发(文本)
  • 原文地址:https://www.cnblogs.com/KevinGeorge/p/8402462.html
Copyright © 2020-2023  润新知