RestFramework之权限组件
2024-08-27 01:39:06
一、权限组件的使用
1.首先需要导入包
from rest_framework.permissions import BasePermission
2.编写权限类
class VipPermission(BasePermission):
message = '无权访问' def has_permission(self, request, view):
if request.user.user_level >= 2:
return True
else:
return False
3.最后在视图中加入一行代码
permission_classes = [VipPermission] # 权限类
也可以在setting中配置:
REST_FRAMEWORK = {
# 序列化
'DEFAULT_PARSER_CLASSES': (
'rest_framework.parsers.JSONParser',
'rest_framework.parsers.FormParser',
'rest_framework.parsers.MultiPartParser'
),
# 认证
'DEFAULT_AUTHENTICATION_CLASSES': (
'app01.utils.auth_class.UserAuth',
),
# 权限
'DEFAULT_PERMISSION_CLASSES': (
'app01.utils.permission_class.VipPermission', # 注意这里是要一个可迭代的,所以逗号不能少
),
}
二、源码剖析
restframework的权限组件与认证组件源码类似,都需要我们自己写一个类,然后放在 permission_classes中,或者全局settings中配置;
我们直接看在dispatch()中的权限组件部分干了什么。
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 request
neg = 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
self.perform_authentication(request)
self.check_permissions(request) # 权限组件
self.check_throttles(request)
再看 self.check_permissions(request):
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)
)
可以看到,这个组件更加简单了,没有封装到request对象中,而是直接放在了APIView中;
根据源码我们写的类需要这么写:需要一个has_permission()的方法,这个方法要是返回True,表示权限认证通过 ; 还可以定义一个message,返回我们自定义的错误信息
验证一下没有权限访问时会怎样:
最新文章
- ffmpeg命令行
- JS采用正则表达式简单获取URL地址栏参数
- Oracle Database 11g Express Edition 使用小结(windows)
- Glibc辅助运行库 (C RunTime Library): crt0.o,crt1.o,crti.o crtn.o,crtbegin.o crtend.o
- 图形变幻矩阵 Transforms
- Java提高篇(三二)-----List总结
- Android实战技术:IPC方式简介教程
- siverlight 后台动态设置图片路径的总结
- MVC源码解析 - Http Pipeline 解析(上)
- 阿里云pai项目使用说明
- Spring MVC 使用介绍(十六)数据验证 (三)分组、自定义、跨参数、其他
- es7 async/await使用
- Ngnix + Tomcat负载均衡架构
- [Leetcode]315.计算右侧小于当前元素的个数 (6种方法)
- innodb_trx, innodb_locks, innodb_lock_waits
- oracle 求班级平均分
- karma配置文件参数介绍
- 获取SQL Server的安装时间
- redis 分布式,主从同步
- 选择客栈(noip2011 day1 t2)