11.DRF-权限

Django rest framework源码分析(2)----权限 添加权限

(1)API/utils文件夹下新建premission.py文件,代码如下:

message是当没有权限时,提示的信息

# utils/permission.py class SVIPPremission(object): message = "必须是SVIP才能访问" def has_permission(self,request,view): if request.user.user_type != 3: return False return True class MyPremission(object): def has_permission(self,request,view): if request.user.user_type == 3: return False return True

(2)settings.py全局配置权限

#全局 REST_FRAMEWORK = { "DEFAULT_AUTHENTICATION_CLASSES":['API.utils.auth.Authentication',], "DEFAULT_PERMISSION_CLASSES":['API.utils.permission.SVIPPremission'], }

(3)views.py添加权限

默认所有的业务都需要SVIP权限才能访问

OrderView类里面没写表示使用全局配置的SVIPPremission

UserInfoView类,因为是普通用户和VIP用户可以访问,不使用全局的,要想局部使用的话,里面就写上自己的权限类

permission_classes = [MyPremission,] #局部使用权限方法

from django.shortcuts import render,HttpResponse from django.http import JsonResponse from rest_framework.views import APIView from API import models from rest_framework.request import Request from rest_framework import exceptions from rest_framework.authentication import BaseAuthentication from API.utils.permission import SVIPPremission,MyPremission ORDER_DICT = { 1:{ 'name':'apple', 'price':15 }, 2:{ 'name':'dog', 'price':100 } } def md5(user): import hashlib import time #当前时间,相当于生成一个随机的字符串 ctime = str(time.time()) m = hashlib.md5(bytes(user,encoding='utf-8')) m.update(bytes(ctime,encoding='utf-8')) return m.hexdigest() class AuthView(APIView): '''用于用户登录验证''' authentication_classes = [] #里面为空,代表不需要认证 permission_classes = [] #不里面为空,代表不需要权限 def post(self,request,*args,**kwargs): ret = {'code':1000,'msg':None} try: user = request._request.POST.get('username') pwd = request._request.POST.get('password') obj = models.UserInfo.objects.filter(username=user,password=pwd).first() if not obj: ret['code'] = 1001 ret['msg'] = '用户名或密码错误' #为用户创建token token = md5(user) #存在就更新,不存在就创建 models.UserToken.objects.update_or_create(user=obj,defaults={'token':token}) ret['token'] = token except Exception as e: ret['code'] = 1002 ret['msg'] = '请求异常' return JsonResponse(ret) class OrderView(APIView): ''' 订单相关业务(只有SVIP用户才能看) ''' def get(self,request,*args,**kwargs): self.dispatch #request.user #request.auth ret = {'code':1000,'msg':None,'data':None} try: ret['data'] = ORDER_DICT except Exception as e: pass return JsonResponse(ret) class UserInfoView(APIView): ''' 订单相关业务(普通用户和VIP用户可以看) ''' permission_classes = [MyPremission,] #不用全局的权限配置的话,这里就要写自己的局部权限 def get(self,request,*args,**kwargs): print(request.user) return HttpResponse('用户信息') # urls.py from django.contrib import admin from django.urls import path from API.views import AuthView,OrderView,UserInfoView urlpatterns = [ path('admin/', admin.site.urls), path('api/v1/auth/',AuthView.as_view()), path('api/v1/order/',OrderView.as_view()), path('api/v1/info/',UserInfoView.as_view()), ] # API/utils/auth/py # auth.py from rest_framework import exceptions from API import models from rest_framework.authentication import BaseAuthentication class Authentication(BaseAuthentication): '''用于用户登录验证''' def authenticate(self,request): token = request._request.GET.get('token') token_obj = models.UserToken.objects.filter(token=token).first() if not token_obj: raise exceptions.AuthenticationFailed('用户认证失败') #在rest framework内部会将这两个字段赋值给request,以供后续操作使用 return (token_obj.user,token_obj) def authenticate_header(self, request): pass

(4)测试

普通用户访问OrderView,提示没有权限

11.DRF-权限

普通用户访问UserInfoView,可以返回信息

11.DRF-权限

权限源码流程

(1)dispatch

def dispatch(self, request, *args, **kwargs): """ `.dispatch()` is pretty much the same as Django's regular dispatch, but with extra hooks for startup, finalize, and exception handling. """ self.args = args self.kwargs = kwargs #对原始request进行加工,丰富了一些功能 #Request( # request, # parsers=self.get_parsers(), # authenticators=self.get_authenticators(), # negotiator=self.get_content_negotiator(), # parser_context=parser_context # ) #request(原始request,[BasicAuthentications对象,]) #获取原生request,request._request #获取认证类的对象,request.authticators #1.封装request request = self.initialize_request(request, *args, **kwargs) self.request = request self.headers = self.default_response_headers # deprecate? try: #2.认证 self.initial(request, *args, **kwargs) # Get the appropriate handler method if request.method.lower() in self.http_method_names: handler = getattr(self, request.method.lower(), self.http_method_not_allowed) else: handler = self.http_method_not_allowed response = handler(request, *args, **kwargs) except Exception as exc: response = self.handle_exception(exc) self.response = self.finalize_response(request, response, *args, **kwargs) return self.response

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:https://www.heiqu.com/wpwysd.html