当前位置:
首页 >
Restful framework【第七篇】权限组件
发布时间:2025/3/14
38
豆豆
生活随笔
收集整理的这篇文章主要介绍了
Restful framework【第七篇】权限组件
小编觉得挺不错的,现在分享给大家,帮大家做个参考.
基本使用
-写一个类: class MyPer(BasePermission):message='您没有权限'def has_permission(self, request, view):# 取出当前登录用户user = request.user# 取出当前登录用户类型的中文tt = user.get_user_type_display()if user.user_type == 0:return Trueelse:return False -局部使用permission_classes=[MyPer] -全局使用在setting中"DEFAULT_PERMISSION_CLASSES":['app01.auth.MyPer'],添加权限
(1)API/utils文件夹下新建premission.py文件,代码如下:
- message是当没有权限时,提示的信息
(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,] #局部使用权限方法
urls.py
from django.contrib import admin from django.urls import path from API.views import AuthView,OrderView,UserInfoViewurlpatterns = [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()), ]auth.py
# API/utils/auth/pyfrom rest_framework import exceptions from API import models from rest_framework.authentication import BaseAuthenticationclass 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,提示没有权限
普通用户访问UserInfoView,可以返回信息
权限源码流程
(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 = argsself.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.封装requestrequest = self.initialize_request(request, *args, **kwargs)self.request = requestself.headers = self.default_response_headers # deprecate?try:#2.认证self.initial(request, *args, **kwargs)# Get the appropriate handler methodif 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_allowedresponse = 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(2)initial
def initial(self, request, *args, **kwargs):"""Runs anything that needs to occur prior to calling the method handler."""self.format_kwarg = self.get_format_suffix(**kwargs)# Perform content negotiation and store the accepted info on the requestneg = self.perform_content_negotiation(request)request.accepted_renderer, request.accepted_media_type = neg# Determine the API version, if versioning is in use.version, scheme = self.determine_version(request, *args, **kwargs)request.version, request.versioning_scheme = version, scheme# Ensure that the incoming request is permitted#4.实现认证self.perform_authentication(request)#5.权限判断self.check_permissions(request)self.check_throttles(request)(3)check_permissions
里面有个has_permission这个就是我们自己写的权限判断
def check_permissions(self, request):"""Check if the request should be permitted.Raises an appropriate exception if the request is not permitted."""#[权限类的对象列表]for permission in self.get_permissions():if not permission.has_permission(request, self):self.permission_denied(request, message=getattr(permission, 'message', None))(4)get_permissions
def get_permissions(self):"""Instantiates and returns the list of permissions that this view requires."""return [permission() for permission in self.permission_classes](5)permission_classes
所以settings全局配置就如下
#全局 REST_FRAMEWORK = {"DEFAULT_PERMISSION_CLASSES":['API.utils.permission.SVIPPremission'], }内置权限
django-rest-framework内置权限BasePermission
默认是没有限制权限
class BasePermission(object):"""A base class from which all permission classes should inherit."""def has_permission(self, request, view):"""Return `True` if permission is granted, `False` otherwise."""return Truedef has_object_permission(self, request, view, obj):"""Return `True` if permission is granted, `False` otherwise."""return True我们自己写的权限类,应该去继承BasePermission,修改之前写的permission.py文件
# utils/permission.pyfrom rest_framework.permissions import BasePermissionclass SVIPPremission(BasePermission):message = "必须是SVIP才能访问"def has_permission(self,request,view):if request.user.user_type != 3:return Falsereturn Trueclass MyPremission(BasePermission):def has_permission(self,request,view):if request.user.user_type == 3:return Falsereturn True总结:
(1)使用
- 自己写的权限类:1.必须继承BasePermission类; 2.必须实现:has_permission方法
(2)返回值
- True 有权访问
- False 无权访问
(3)局部
- permission_classes = [MyPremission,]
(4)全局
REST_FRAMEWORK = {#权限"DEFAULT_PERMISSION_CLASSES":['API.utils.permission.SVIPPremission'], }
转载于:https://www.cnblogs.com/596014054-yangdongsheng/p/10402986.html
与50位技术专家面对面20年技术见证,附赠技术全景图总结
以上是生活随笔为你收集整理的Restful framework【第七篇】权限组件的全部内容,希望文章能够帮你解决所遇到的问题。
- 上一篇: 简单的数学题
- 下一篇: Codeforces 524E Rook