django实现自定义登陆验证
- 自定义装饰器函数和类
-
1 from utils.http import HttpResponseUnauthorized 2 from django.views import View 3 4 5 6 7 # 登陆校验装饰器 函数视图校验 8 def login_require(func): 9 def wrapper(request): 10 11 # 校验session中是否存在login_flag 12 login_flag = request.session.get('login_flag') 13 14 if not login_flag: 15 return HttpResponseUnauthorized('用户未登录') 16 17 result = func(request) 18 return result 19 20 return wrapper 21 22 23 # 登陆校验视图类 类视图校验 24 class LoginRequireMixin(View): 25 @classmethod 26 def as_view(cls, **initkwargs): 27 # 对父类的as_view进行改写并封装 28 view = super(LoginRequireMixin, cls).as_view(**initkwargs) 29 return login_require(view)
-
HttpResponseUnauthorized
1 from django.http import HttpResponse 2 3 4 5 class HttpResponseUnauthorized(HttpResponse): 6 status_code = 401
- 具体使用
-
1 # 保存成绩 2 @login_require 3 def saveScore(request): 4 if request.method == 'POST': 5 6 open_id = request.POST.get('open_id') 7 nickName = request.POST.get('nickName') 8 gameType = request.POST.get('gameType') 9 spendTime = request.POST.get('spendTime') 10 ageType = request.POST.get('ageType') 11 12 if not all([open_id, nickName, gameType, spendTime, ageType]): 13 date = {'success': False, 'info': '请求数据不完整'} 14 return JsonResponse(date) 15 16 if request.session.get('openId') != open_id: 17 data = {'success': False, 'info': '请求玩家和使用玩家不一致'} 18 return JsonResponse(data) 19 20 Score(open_id=open_id, nickName=nickName, gameType=gameType, spendTime=spendTime, ageType=ageType).save() 21 data = {'success': True, 'info': '保存成功!'} 22 return JsonResponse(data) 23 24 return HttpResponseForbidden('Method not allowed') 25 26 27 # 分类成绩查询 28 class RankingQuery(LoginRequireMixin): 29 30 def post(self, request): 31 queryType = request.POST.get('queryType') 32 offset = request.POST.get('offset') 33 34 if not all([queryType, offset]): 35 data = {'success': False, 'info': '数据不完整'} 36 return JsonResponse(data) 37 38 queryTypeRoute = { 39 'byScore': self.queryByScore 40 } 41 if queryType not in queryTypeRoute: 42 return HttpResponseBadRequest('unsupport queryType') 43 44 func = queryTypeRoute['queryType'] 45 data = func(offset) 46 47 return JsonResponse(data)