侯体宗的博客
  • 首页
  • Hyperf版
  • beego仿版
  • 人生(杂谈)
  • 技术
  • 关于我
  • 更多分类
    • 文件下载
    • 文字修仙
    • 中国象棋ai
    • 群聊
    • 九宫格抽奖
    • 拼图
    • 消消乐
    • 相册

Django-Rest-Framework 权限管理源码浅析(小结)

框架(架构)  /  管理员 发布于 7年前   193

在django的views中不论是用类方式还是用装饰器方式来使用rest框架,django_rest_frame实现权限管理都需要两个东西的配合: authentication_classes 和 permission_classes

# 方式1: 装饰器from rest_framework.decorators import api_view, authentication_classes, permission_classesfrom rest_framework.authentication import SessionAuthentication, BasicAuthenticationfrom rest_framework.permissions import AllowAnyfrom rest_framework.response import Response@api_view(["GET", ])@permission_classes([AllowAny,])@authentication_classes([SessionAuthentication, BasicAuthentication])def test_example(request): content = {   'user': unicode(request.user), # `django.contrib.auth.User` instance.   'auth': unicode(request.auth), # None  }  return Response(content)# ------------------------------------------------------------# 方式2: 类from rest_framework.authentication import SessionAuthentication, BasicAuthenticationfrom rest_framework.permissions import AllowAnyfrom rest_framework.response import Responsefrom rest_framework.views import APIViewclass ExampleView(APIView): authentication_classes = (SessionAuthentication, BasicAuthentication) permission_classes = (AllowAny,) def get(self, request, format=None):  content = {   'user': unicode(request.user), # `django.contrib.auth.User` instance.   'auth': unicode(request.auth), # None  }  return Response(content)

上面给出的是权限配置的默认方案,写和不写没有区别。 rest框架有自己的settings文件 ,最原始的默认值都可以在里面找到:

说道rest的settings文件,要覆盖其中的默认行为,特别是权限认证行为,我们只需要在 项目settings文件

中指定你自己的类即可:

REST_FRAMEWORK = { ... 'DEFAULT_AUTHENTICATION_CLASSES': (  'your_authentication_class_path', ), ...}

在rest的settings文件中,获取属性时,会优先加载项目的settings文件中的设置,如果项目中没有的,才加载自己的默认设置:

初始化api_settings对象

api_settings = APISettings(None, DEFAULTS, IMPORT_STRINGS)

APISettings 类中获取属性时优先获取项目的settings文件中 REST_FRAMEWORK 对象的值,没有的再找自己的默认值

@propertydef user_settings(self): if not hasattr(self, '_user_settings'):  # _user_settings默认为加载项目settings文件中的REST_FRAMEWORK对象  self._user_settings = getattr(settings, 'REST_FRAMEWORK', {}) return self._user_settingsdef __getattr__(self, attr): if attr not in self.defaults:  raise AttributeError("Invalid API setting: '%s'" % attr) try:  # Check if present in user settings  # 优先加载user_settings,即项目的settings文件,没有就用默认  val = self.user_settings[attr] except KeyError:  # Fall back to defaults  val = self.defaults[attr] # Coerce import strings into classes if attr in self.import_strings:  val = perform_import(val, attr) # Cache the result self._cached_attrs.add(attr) setattr(self, attr, val) return val

在rest中settings中,能自动检测 项目settings 的改变,并重新加载自己的配置文件:

权限管理原理浅析

rest框架是如何使用 authentication_classes 和 permission_classes ,并将二者配合起来进行权限管理的呢?

使用类方式实现的时候,我们都会直接或间接的使用到rest框架中的APIVIEW,在 urls.py 中使用该类的 as_view 方法来构建router

# views.pyfrom rest_framework.views import APIViewfrom rest_framework.permissions import IsAuthenticatedclass ExampleAPIView(APIView): permission_classes = (IsAuthenticated,) ... # -----------------------------from django.conf.urls import url, includefrom .views import ExampleAPIViewurlpatterns = [ url(r'^example/(?P<example_id>[-\w]+)/examples/?$',  ExampleAPIView.as_view()),]

在我们调用 APIVIEW.as_view() 的时候,该类会调用父类的同名方法:

父类的同名方法中,调用了dispatch方法:

rest 重写 了该方法,在该方法中对requset做了一次服务端初始化(加入验证信息等)处理

调用权限管理

在权限管理中会使用默认的或是你指定的权限认证进行验证: 这里只是做验证并存储验证结果 ,这里操作完后authentication_classes的作用就完成了。验证结果会在后面指定的 permission_classes 中使用!

def get_authenticators(self):  """  Instantiates and returns the list of authenticators that this view can use.  """  return [auth() for auth in self.authentication_classes]

通过指定的permission_classes确定是否有当前接口的访问权限:

class IsAuthenticatedOrReadOnly(BasePermission): """ The request is authenticated as a user, or is a read-only request. """ def has_permission(self, request, view):  return (   request.method in SAFE_METHODS or   request.user and   request.user.is_authenticated  )

最后,不管有没有使用permission_classes来决定是否能访问,默认的或是你自己指定的authentication_classes都会执行并将权限结果放在request中!

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。


  • 上一条:
    Django跨域请求CSRF的方法示例
    下一条:
    详解django自定义中间件处理
  • 昵称:

    邮箱:

    0条评论 (评论内容有缓存机制,请悉知!)
    最新最热
    • 分类目录
    • 人生(杂谈)
    • 技术
    • linux
    • Java
    • php
    • 框架(架构)
    • 前端
    • ThinkPHP
    • 数据库
    • 微信(小程序)
    • Laravel
    • Redis
    • Docker
    • Go
    • swoole
    • Windows
    • Python
    • 苹果(mac/ios)
    • 相关文章
    • Filament v3.1版本发布(0个评论)
    • docker + gitea搭建一个git服务器流程步骤(0个评论)
    • websocket的三种架构方式使用优缺点浅析(0个评论)
    • ubuntu20.4系统中宿主机安装nginx服务,docker容器中安装php8.2实现运行laravel10框架网站(0个评论)
    • phpstudy_pro(小皮面板)中安装最新php8.2.9版本流程步骤(0个评论)
    • 近期文章
    • 在go中实现一个常用的先进先出的缓存淘汰算法示例代码(0个评论)
    • 在go+gin中使用"github.com/skip2/go-qrcode"实现url转二维码功能(0个评论)
    • 在go语言中使用api.geonames.org接口实现根据国际邮政编码获取地址信息功能(1个评论)
    • 在go语言中使用github.com/signintech/gopdf实现生成pdf分页文件功能(0个评论)
    • gmail发邮件报错:534 5.7.9 Application-specific password required...解决方案(0个评论)
    • 欧盟关于强迫劳动的规定的官方举报渠道及官方举报网站(0个评论)
    • 在go语言中使用github.com/signintech/gopdf实现生成pdf文件功能(0个评论)
    • Laravel从Accel获得5700万美元A轮融资(0个评论)
    • 在go + gin中gorm实现指定搜索/区间搜索分页列表功能接口实例(0个评论)
    • 在go语言中实现IP/CIDR的ip和netmask互转及IP段形式互转及ip是否存在IP/CIDR(0个评论)
    • 近期评论
    • 122 在

      学历:一种延缓就业设计,生活需求下的权衡之选中评论 工作几年后,报名考研了,到现在还没认真学习备考,迷茫中。作为一名北漂互联网打工人..
    • 123 在

      Clash for Windows作者删库跑路了,github已404中评论 按理说只要你在国内,所有的流量进出都在监控范围内,不管你怎么隐藏也没用,想搞你分..
    • 原梓番博客 在

      在Laravel框架中使用模型Model分表最简单的方法中评论 好久好久都没看友情链接申请了,今天刚看,已经添加。..
    • 博主 在

      佛跳墙vpn软件不会用?上不了网?佛跳墙vpn常见问题以及解决办法中评论 @1111老铁这个不行了,可以看看近期评论的其他文章..
    • 1111 在

      佛跳墙vpn软件不会用?上不了网?佛跳墙vpn常见问题以及解决办法中评论 网站不能打开,博主百忙中能否发个APP下载链接,佛跳墙或极光..
    • 2018-05
    • 2020-02
    • 2020-03
    • 2020-05
    • 2020-06
    • 2020-07
    • 2020-08
    • 2020-11
    • 2021-03
    • 2021-09
    • 2021-10
    • 2021-11
    • 2022-01
    • 2022-02
    • 2022-03
    • 2022-08
    • 2023-08
    • 2023-10
    • 2023-12
    Top

    Copyright·© 2019 侯体宗版权所有· 粤ICP备20027696号 PHP交流群

    侯体宗的博客