脚本之家,脚本语言编程技术及教程分享平台!
分类导航

Python|VBS|Ruby|Lua|perl|VBA|Golang|PowerShell|Erlang|autoit|Dos|bat|

服务器之家 - 脚本之家 - Python - Django-Rest-Framework 权限管理源码浅析(小结)

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

2021-04-18 00:45行行出bug Python

这篇文章主要介绍了Django-Rest-Framework 权限管理源码浅析(小结),小编觉得挺不错的,现在分享给大家,也给大家做个参考。一起跟随小编过来看看吧

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

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
# 方式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文件 ,最原始的默认值都可以在里面找到:

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

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

中指定你自己的类即可:

?
1
2
3
4
5
6
7
rest_framework = {
 ...
 'default_authentication_classes': (
  'your_authentication_class_path',
 ),
 ...
}

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

初始化api_settings对象

?
1
api_settings = apisettings(none, defaults, import_strings)

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

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
@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 的改变,并重新加载自己的配置文件:

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

权限管理原理浅析

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

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

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
# 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() 的时候,该类会调用父类的同名方法:

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

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

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

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

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

调用权限管理

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

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

?
1
2
3
4
5
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确定是否有当前接口的访问权限:

?
1
2
3
4
5
6
7
8
9
10
11
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

延伸 · 阅读

精彩推荐