现有如下检查登录装饰器:
from functools import wraps def check_login(func):
@wraps(func)
def inner(request, *args, **kwargs):
next_url = request.get_full_path()
if request.session.get("user"):
return func(request, *args, **kwargs)
else:
return redirect("/login/?next={}".format(next_url))
return inner
Code
使用
要在CBV视图中使用我们上面的check_login装饰器,有以下三种方式:
加在的get或post方法上
from django.utils.decorators import method_decorator class HomeView(View): def dispatch(self, request, *args, **kwargs):
return super(HomeView, self).dispatch(request, *args, **kwargs) def get(self, request):
return render(request, "home.html") @method_decorator(check_login)
def post(self, request):
print("Home View POST method...")
return redirect("/index/")
Code
加在dispatch方法上
from django.utils.decorators import method_decorator class HomeView(View): @method_decorator(check_login)
def dispatch(self, request, *args, **kwargs):
return super(HomeView, self).dispatch(request, *args, **kwargs) def get(self, request):
return render(request, "home.html") def post(self, request):
print("Home View POST method...")
return redirect("/index/")
Code
因为CBV中首先执行的就是dispatch方法,所以这么写相当于给get和post方法都加上了登录校验。
加在视图类上
直接加在视图类上,但method_decorator必须传name关键字参数。如果get方法和post方法都需要登录校验的话就写两个装饰器。
from django.utils.decorators import method_decorator @method_decorator(check_login, name="get")
@method_decorator(check_login, name="post")
class HomeView(View): def dispatch(self, request, *args, **kwargs):
return super(HomeView, self).dispatch(request, *args, **kwargs) def get(self, request):
return render(request, "home.html") def post(self, request):
print("Home View POST method...")
return redirect("/index/")
Code
补充
CSRF Token相关装饰器
-
csrf_protect
为当前函数强制设置防跨站请求伪造功能,即便settings中没有设置全局中间件。
-
csrf_exempt
取消当前函数防跨站请求伪造功能,即便settings中设置了全局中间件。
-
使用
CSRF Token相关装饰器在CBV只能加到dispatch方法上,或者加在视图类上然后name参数指定为dispatch方法。
from django.views.decorators.csrf import csrf_exempt, csrf_protect
from django.utils.decorators import method_decorator class HomeView(View): @method_decorator(csrf_exempt)
def dispatch(self, request, *args, **kwargs):
return super(HomeView, self).dispatch(request, *args, **kwargs) def get(self, request):
return render(request, "home.html") def post(self, request):
print("Home View POST method...")
return redirect("/index/")加到dispatch方法上
from django.views.decorators.csrf import csrf_exempt, csrf_protect
from django.utils.decorators import method_decorator @method_decorator(csrf_exempt, name='dispatch')
class HomeView(View): def dispatch(self, request, *args, **kwargs):
return super(HomeView, self).dispatch(request, *args, **kwargs) def get(self, request):
return render(request, "home.html") def post(self, request):
print("Home View POST method...")
return redirect("/index/")加在视图类上