在使用装饰器验证用户是否登录的时候,装饰器函数里面用到了request参数,从request.session中获取用户是否登录。运行时报错。
# 装饰器函数代码
def auth(func):
def inner(request, *args, **kwargs):
if request.session.get('is_login', None):
response = func(request, *args, **kwargs)
return response
else:
return render(request, 'login.html')
return inner
# view视图函数代码
class JenkinsLoginView(View):
@auth
def get(self,request):
nick = request.session.get('nick')
if request.session.get('j_login', None):
jip_port = request.session['jip_port']
jtitle = '已登录:' + jip_port
return render(request, 'jenkins/jenkins_login.html', {'nick': nick, 'jtitle': jtitle})
报错是因为@auth用法错误。
解决办法改为:
from django.utils.decorators import method_decorator
@method_decorator(auth)