FBV中的示例:
在views.py中
# 用户认证的装饰器
def auth(func):
def inner(request, *args, **kwargs):
v = request.COOKIES.get('username')
if not v:
return redirect('/login/')
return func(request, *args, **kwargs)
return inner
@auth
def index(request):
# 获取当前已经登录的用户名
v = request.COOKIES.get('username')
print v
if not v:
return redirect('/cookie/login/')
return render(request, 'cookie/index.html', {'current_user':v})
CBV中的示例
# 方法1
from django.utils.decorators import method_decorator
class Order(views.View):
@method_decorator(auth)
def get(self, request):
pass
@method_decorator(auth)
def post(self, request):
pass
# 方法2
from django.utils.decorators import method_decorator
class Order(views.View):
@method_decorator(auth)
def dispatch(self, request, *args, **kwargs):
return super(Order, self).dispatch(request, *args, **kwargs)
def get(self, request):
pass
def post(self, request):
pass
# 方法3
from django.utils.decorators import method_decorator
@method_decorator(auth, name='dispatch')
class Order(views.View):
#def dispatch(self, request, *args, **kwargs):
# return super(Order, self).dispatch(request, *args, **kwargs)
def get(self, request):
pass
def post(self, request):
pass
网友评论