11.DRF-許可權
阿新 • • 發佈:2020-06-21
## Django rest framework原始碼分析(2)----許可權
### 新增許可權
(1)API/utils資料夾下新建premission.py檔案,程式碼如下:
- message是當沒有許可權時,提示的資訊
```python
# utils/permission.py
class SVIPPremission(object):
message = "必須是SVIP才能訪問"
def has_permission(self,request,view):
if request.user.user_type != 3:
return False
return True
class MyPremission(object):
def has_permission(self,request,view):
if request.user.user_type == 3:
return False
return True
```
(2)settings.py全域性配置許可權
```python
#全域性
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,] #區域性使用許可權方法
```python
from django.shortcuts import render,HttpResponse
from django.http import JsonResponse
from rest_framework.views import APIView
from API import models
from rest_framework.request import Request
from rest_framework import exceptions
from rest_framework.authentication import BaseAuthentication
from API.utils.permission import SVIPPremission,MyPremission
ORDER_DICT = {
1:{
'name':'apple',
'price':15
},
2:{
'name':'dog',
'price':100
}
}
def md5(user):
import hashlib
import time
#當前時間,相當於生成一個隨機的字串
ctime = str(time.time())
m = hashlib.md5(bytes(user,encoding='utf-8'))
m.update(bytes(ctime,encoding='utf-8'))
return m.hexdigest()
class AuthView(APIView):
'''用於使用者登入驗證'''
authentication_classes = [] #裡面為空,代表不需要認證
permission_classes = [] #不裡面為空,代表不需要許可權
def post(self,request,*args,**kwargs):
ret = {'code':1000,'msg':None}
try:
user = request._request.POST.get('username')
pwd = request._request.POST.get('password')
obj = models.UserInfo.objects.filter(username=user,password=pwd).first()
if not obj:
ret['code'] = 1001
ret['msg'] = '使用者名稱或密碼錯誤'
#為使用者建立token
token = md5(user)
#存在就更新,不存在就建立
models.UserToken.objects.update_or_create(user=obj,defaults={'token':token})
ret['token'] = token
except Exception as e:
ret['code'] = 1002
ret['msg'] = '請求異常'
return JsonResponse(ret)
class OrderView(APIView):
'''
訂單相關業務(只有SVIP使用者才能看)
'''
def get(self,request,*args,**kwargs):
self.dispatch
#request.user
#request.auth
ret = {'code':1000,'msg':None,'data':None}
try:
ret['data'] = ORDER_DICT
except Exception as e:
pass
return JsonResponse(ret)
class UserInfoView(APIView):
'''
訂單相關業務(普通使用者和VIP使用者可以看)
'''
permission_classes = [MyPremission,] #不用全域性的許可權配置的話,這裡就要寫自己的區域性許可權
def get(self,request,*args,**kwargs):
print(request.user)
return HttpResponse('使用者資訊')
```
```python
# urls.py
from django.contrib import admin
from django.urls import path
from API.views import AuthView,OrderView,UserInfoView
urlpatterns = [
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()),
]
```
```python
# API/utils/auth/py
# auth.py
from rest_framework import exceptions
from API import models
from rest_framework.authentication import BaseAuthentication
class 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,提示沒有許可權
![](https://img2020.cnblogs.com/blog/1988132/202006/1988132-20200621114611413-1097628830.png)
普通使用者訪問UserInfoView,可以返回資訊
![](https://img2020.cnblogs.com/blog/1988132/202006/1988132-20200621114622412-41821800.png)
### 許可權原始碼流程
(1)dispatch
```python
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 = args
self.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.封裝request
request = self.initialize_request(request, *args, **kwargs)
self.request = request
self.headers = self.default_response_headers # deprecate?
try:
#2.認證
self.initial(request, *args, **kwargs)
# Get the appropriate handler method
if 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_allowed
response = 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
```python
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
#4.實現認證
self.perform_authentication(request)
#5.許可權判斷
self.check_permissions(request)
self.check_throttles(request)
```
(3)check_permissions
裡面有個has_permission這個就是我們自己寫的許可權判斷
```python
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
```python
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
![](https://img2020.cnblogs.com/blog/1988132/202006/1988132-20200621114651363-1564145489.png)
所以settings全域性配置就如下
```python
#全域性
REST_FRAMEWORK = {
"DEFAULT_PERMISSION_CLASSES":['API.utils.permission.SVIPPremission'],
}
```
### 內建許可權
django-rest-framework內建許可權BasePermission
預設是沒有限制許可權
```python
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 True
def has_object_permission(self, request, view, obj):
"""
Return `True` if permission is granted, `False` otherwise.
"""
return True
```
我們自己寫的許可權類,應該去繼承BasePermission,修改之前寫的permission.py檔案
```python
# utils/permission.py
from rest_framework.permissions import BasePermission
class SVIPPremission(BasePermission):
message = "必須是SVIP才能訪問"
def has_permission(self,request,view):
if request.user.user_type != 3:
return False
return True
class MyPremission(BasePermission):
def has_permission(self,request,view):
if request.user.user_type == 3:
return False
return True
```
### 總結:
(1)使用
- 自己寫的許可權類:1.必須繼承BasePermission類; 2.必須實現:has_permission方法
(2)返回值
- True 有權訪問
- False 無權訪問
(3)區域性
- permission_classes = [MyPremission,]
(4)全域性
```python
REST_FRAMEWORK = {
#許可權
"DEFAULT_PERMISSION_CLASSES":['API.utils.permission.SVIPPremission']