Django-Rest-Framework 权限管理源码浅析(小结)
作者:行行出bug 发布时间:2021-11-02 06:18:49
在django的views中不论是用类方式还是用装饰器方式来使用rest框架,django_rest_frame实现权限管理都需要两个东西的配合: authentication_classes
和 permission_classes
# 方式1: 装饰器
from rest_framework.decorators import api_view, authentication_classes, permission_classes
from rest_framework.authentication import SessionAuthentication, BasicAuthentication
from rest_framework.permissions import AllowAny
from 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, BasicAuthentication
from rest_framework.permissions import AllowAny
from rest_framework.response import Response
from rest_framework.views import APIView
class 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
对象的值,没有的再找自己的默认值
@property
def user_settings(self):
if not hasattr(self, '_user_settings'):
# _user_settings默认为加载项目settings文件中的REST_FRAMEWORK对象
self._user_settings = getattr(settings, 'REST_FRAMEWORK', {})
return self._user_settings
def __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.py
from rest_framework.views import APIView
from rest_framework.permissions import IsAuthenticated
class ExampleAPIView(APIView):
permission_classes = (IsAuthenticated,)
...
# -----------------------------
from django.conf.urls import url, include
from .views import ExampleAPIView
urlpatterns = [
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中!
来源:https://juejin.im/post/5be8f771f265da611c2680a0


猜你喜欢
- 本文实例讲述了Go语言实现简单留言板的方法。分享给大家供大家参考。具体实现方法如下:package mainimport ( &n
- 一、MySQL数据库的实例管理器概述:1、MySQL数据库的实例管理器(IM)是通过TCP/IP端口运行的后台程序,用来监视和管理MySQL
- 在用mysql时(show tables),有时候需要查看表和字段的相关信息(表与某字段是否存在等.)~~而PHP提供了这样的相关函数,如:
- 1、php支持哪些数据库(拥有哪些数据库接口)Adabas D ,InterBase ,PostgreSQL ,dBase ,FrontBa
- 目录前言1.使用全局统一覆盖2.在.vue文件中修改3.修改组件的style样式4. 参考element-ui官方文档的api疑问总结前言修
- 在使用python函数print()时,如下代码会出现输出无法显示的问题:分三次在一行输出 123print(1, end="&q
- ubuntu上安装mysql非常简单只需要几条命令就可以完成。1. sudo apt-get install mysql-server2.
- 短几年,Google 的 Logo 已经象 Nike 的挑勾和 NBC 的孔雀图案一样著名了。Ruth Kedar,Google
- 原理:TensorFlow使用的求导方法称为自动微分(Automatic Differentiation),它既不是符号求导也不是数值求导,
- 目的:方便调试,查看中间结果,因为觉得设断点调试相对麻烦。【运行环境:macOS 10.13.3,PyCharm 2017.2.4】老手:选
- Exec sp_droplinkedsrvlogin ZYB,Null --删除映射(录与链接服务器上远程登录之间的映射) Exec sp_
- 摘要如何用beautifulsoup4解析各种情况的网页beautifulsoup4的使用关于beautifulsoup4,官网已经讲的很详
- 序 号前 缀使用的变量/范围或数据类型1a or arrArray2b or blnBoolean3bytByte4
- 背景:实现用python的optimize库的fsolve对非线性方程组进行求解。可以看到这一个问题实际上还是一个优化问题,也可以用之前拟合
- importlib 模块的作用模块,是一个一个单独的py文件 包,里面包含多个模块(py文件)动态导入模块,这样就不用写那么多的import
- 导语昨天下班,回家吃完饭就直接躺了,无聊的时候大家都会干什么呢?当然是刷刷刷——抖音啦,嗯哼,然后返现了抖音上一款特效——「变身漫画」,简直
- 如何在Typescript中使用for...in ?本人在TS中用for...in出现了些问题,也想到了一些解决方法。那么先来看看下面报错的
- 1.首先要绘制一个简单的条形图import numpy as npimport matplotlib.pyplot as pltfrom m
- 在装这两个的时候出现一些问题,最后总算成功了,记录一下过程环境:win10 64位系统,python3.7.8 ,pip18下载地址:这两个
- 前言网络爬虫(又被称为网页蜘蛛,网络机器人,在FOAF社区中间,更经常的称为网页追逐者),是一种按照一定的规则,自动地抓取万维网信息的程序或