- from django.utils.decorators import method_decorator导入django自带的注册装饰器的函数
- 以下是校验登陆的装饰器函数
def CheckLogin(func):def CheckLogin(func):
def warpper(request, *args, **kwargs):
if ‘user_id’ in request.session:
return func(request, *args, **kwargs)
else:
response = redirect(reverse(“user:login”))
response.set_cookie(“url”, request.path, 7 * 24 * 3600)
return response
return warpper - 在需要校验登陆的函数上面加入装饰器
@method_decorator(CheckLogin)
通过以上三步就可以实现django装饰器检验登陆的状态
说明:
1. func(request, *args, **kwargs)是被装饰的函数,不能缺少了request,
2. 在func前一定要加return返回,要不然会报网页没有返回值的错误
3. 还有一定要django自带的装饰器注册函数进行注册,要不然会报request未定义的错误