django自定义实现登录验证
django内置的登录验证必须让开发者使用django内置的User模块,这会让开发者再某些方面被限制住
下面的模块是我自己自定义实现的django验证,使用方式和django的一样
1 from django.http import HttpResponse 2 from django.shortcuts import redirect 3 from django.conf import settings 4 from django.views import View 5 6 7 class HttpResponseUnauthorized(HttpResponse): 8 status_code = 401 9 10 11 def login(request, user): 12 request.session[\'login\'] = user.id 13 14 15 def logout(request): 16 request.session.flush() 17 18 19 def login_required(func): 20 """ 21 对需要登录的视图函数进行验证 22 @login_required 23 def your_view(request, *args, **kwargs): 24 \'\'\'\'\'\' 25 """ 26 27 def wrapper(*args, **kwargs): 28 request = args[0] 29 is_login = request.session.get(\'login\') 30 31 if not is_login: 32 redirect_url = \'%s?next=%s\' % (settings.LOGIN_URL, request.path) 33 return redirect(redirect_url) 34 else: 35 result = func(*args, **kwargs) 36 return result 37 38 return wrapper 39 40 41 class LoginRequired(View): 42 """ 43 对需要登录的类视图进行验证 44 class YouView(LoginRequired): 45 \'\'\'\'\'\' 46 """ 47 48 @classmethod 49 def as_view(cls, **initkwargs): 50 view = super(LoginRequired, cls).as_view() 51 return login_required(view)