CBV(class base view)
基于session实现的装饰器:
登录了就给session设置值(生成随机序列),然后存入数据库,并将一串随机序列键值对返回给浏览器端,若未登录则跳转到登录页面。
def login_auth(func):
@wraps(func)
def inner(request,*args,**kwargs):
if request.session.get('name'):
return func(request,*args,**kwargs)
return redirect('/login/')
return inner
类视图装饰器:
主要有三种装饰位置:
from django.utils.decorators import method_decorator
method_decorator这是一个函数:将函数装饰器转换为方法装饰器
Converts a function decorator into a method decorator
有三种方式装饰类:
-
第一种:就是装饰指定函数:
@method_decorator(login_auth,name=“post”) -
第二种:就是装饰整个类中函数:
@method_decorator(login_auth,name=“dispatch”)
因为dispath是用于分发的,因此我们通过重写dispatch来控制分发,控制了dispatch就等于控制了所有的类中函数。 -
第三种装饰的
@method_decorator(login_auth)
def dispatch(self, request, *args, **kwargs):
super().dispatch(request, *args, **kwargs)
dispatch源码def dispatch(self, request, *args, **kwargs): # Try to dispatch to the right method; if a method doesn't exist, # defer to the error handler. Also defer to the error handler if the # request method isn't on the approved list. if request.method.lower() in self.http_method_names: handler = getattr(self, request.method.lower(), self.http_method_not_allowed) else: handler = self.http_method_not_allowed return handler(request, *args, **kwargs)
简单登录的跳转的代码
from django.shortcuts import render,HttpResponse,redirect,reverse
from functools import wraps
from django.utils.decorators import method_decorator
def login(request):
#登录判断用户名与密码是否正确
if request.method == "POST":
username = request.POST.get("username")
pwd = request.POST.get("pwd")
if username == 'jeason' and pwd == '123':
#用户名密码正确了就给session赋值,然后session将生成密码序列存于数据库中,并转发给浏览器端,
request.session['name'] = 'jeason'
return redirect('/home/')
return render(request,'login.html')
#登录装饰器,当你的session中有值说明你已经登录了,跳转到home,若是没有值则回到登录
def login_auth(func):
@wraps(func)
def inner(request,*args,**kwargs):
if request.session.get('name'):
return func(request,*args,**kwargs)
return redirect('/login/')
return inner
#类装饰器三种方式,装饰单个函数,与装饰dispatch,dispatch中执行的判断请求类型,
在View类中反射出View中的Post或者get等方法,然后执行函数。
from django.views import View
# @method_decorator(login_auth,name='post')
class MyHome(View):
@method_decorator(login_auth)
def dispatch(self, request, *args, **kwargs):
super().dispatch(request, *args, **kwargs)
# @method_decorator(login_auth)
def get(self,request):
return HttpResponse("get")
def post(self,request):
return HttpResponse("post")
urls.py中代码如下:
url(r'^home/', views.MyHome.as_view()),
url(r'^login/', views.login),