Django REST framwork的權限驗證實例
在這里插入代碼片# Django REST framwork的權限驗證
一、用戶是否登錄
(1)判斷用戶是否登錄;
permission_classes = (IsAuthenticated, )
注意:permission_classes設置的是:驗證的是用戶是否登錄、用戶是否可以操作該數據等的權限;
權限組合方式,目前支持:與&(and) 或|(or) 非~(not)
例如:permission_classes = (SecAdminPermission | AudAdminPermission,)
注意:使用元組 (SecAdminPermission | AudAdminPermission,)或列表[ SecAdminPermission | AudAdminPermission]都可以。
(2)設置用戶認證方式;
authentication_classes = (JSONWebTokenAuthentication, SessionAuthentication)
注意:authentication_classes設置的是:用戶可以通過哪種方式登錄系統(tǒng),例如:JWT或傳統(tǒng)的用戶名+密碼方式登錄。
具體代碼如下:
from rest_framework.permissions import IsAuthenticated # 判斷用戶是否登錄
from rest_framework_jwt.authentication import JSONWebTokenAuthentication # jwt用戶認證
class UserFavViewset(mixins.CreateModelMixin, mixins.ListModelMixin, mixins.RetrieveModelMixin,
mixins.DestroyModelMixin, viewsets.GenericViewSet):
"""
list:
獲取用戶收藏列表
retrieve:
判斷某個商品是否已經收藏
create:
收藏商品
delete:
取消收藏
"""
# 權限判斷:IsAuthenticated表示是否已經登錄,IsOwnerOrReadOnly表示數據是不是屬于當前登錄用戶
permission_classes = (IsAuthenticated, IsOwnerOrReadOnly)
# 用戶認證:方式一:JSONWebTokenAuthentication;方式二:SessionAuthentication
authentication_classes = (JSONWebTokenAuthentication, SessionAuthentication)
# 定義通過哪個參數來定位實例
lookup_field = "goods_id" # 在詳細頁面時,搜索goods_id來確認該商品有沒有被收藏,是在當前用戶下進行搜索的
def get_queryset(self):
"""獲取當前登錄用戶的收藏信息"""
return UserFav.objects.filter(user=self.request.user)
# 方法一:修改商品收藏數
# def perform_create(self, serializer):
# """修改商品收藏數"""
# instance = serializer.save()
# goods = instance.goods
# goods.fav_num += 1
# goods.save()
# 動態(tài)設置序列化類
def get_serializer_class(self):
if self.action == "list":
return UserFavDetailSerializer
elif self.action == "create":
return UserFavSerializer
return UserFavSerializer
二、用戶是否對該數據有操作權限;
(1)自定義權限驗證
前提:待驗證對象有user字段;
from rest_framework import permissions # 權限判斷:數據是不是屬于當前登錄用戶 class IsOwnerOrReadOnly(permissions.BasePermission): """ Object-level permission to only allow owners of an object to edit it. Assumes the model instance has an `owner` attribute. """ def has_object_permission(self, request, view, obj): # 1 只讀 # Read permissions are allowed to any request, # so we'll always allow GET, HEAD or OPTIONS requests. if request.method in permissions.SAFE_METHODS: # 是不是安全的訪問方法 return True # 2 寫權限 # Instance must have an attribute named `owner`. # return (obj.publisher if obj.publisher else self.fans )== request.user return obj.user== request.user # 判斷當前數據是不是登錄用戶的數據
(2)在接口中,添加數據權限驗證;
class UserFavViewset(mixins.CreateModelMixin, mixins.ListModelMixin, mixins.RetrieveModelMixin,
mixins.DestroyModelMixin, viewsets.GenericViewSet):
"""
list:
獲取用戶收藏列表
retrieve:
判斷某個商品是否已經收藏
create:
收藏商品
delete:
取消收藏
"""
# 權限判斷:IsAuthenticated表示是否已經登錄,IsOwnerOrReadOnly表示數據是不是屬于當前登錄用戶
permission_classes = (IsAuthenticated, IsOwnerOrReadOnly)
# 用戶認證:方式一:JSONWebTokenAuthentication;方式二:SessionAuthentication
authentication_classes = (JSONWebTokenAuthentication, SessionAuthentication)
# 設置
lookup_field = "goods_id" # 在詳細頁面時,搜索goods_id來確認該商品有沒有被收藏,是在當前用戶下進行搜索的
def get_queryset(self):
"""獲取當前登錄用戶的收藏信息"""
return UserFav.objects.filter(user=self.request.user)
補充知識:django rest framework api授權與認證
djangorestf 官方文檔 授權與認證教程
permissions.py
from rest_framework import permissions
class IsOwnerOrReadOnly(permissions.BasePermission):
'''
常規(guī)的授權是 只有擁有者才能編輯它
'''
def has_object_permission(self, request, view, obj):
# 讀權限 向所有請求開放
# 所以我們總是允許get, head or options requests.
if request.method in permissions.SAFE_METHODS:
return True
# 寫權限 只給擁有者
return obj.owner == request.user
view.py
'''基于泛型類的視圖'''
from snippets.models import Snippet
from snippets.serializers import SnippetSerializer, UserSerializer
from rest_framework import generics
from snippets.permissions import IsOwnerOrReadOnly
from django.contrib.auth.models import User
class UserList(generics.ListAPIView):
'''
User表的列表api視圖 查 增 操作
'''
queryset = User.objects.all()
serializer_class = UserSerializer
class UserDetail(generics.RetrieveDestroyAPIView):
'''
User表的詳情api視圖 查 改 刪操作
'''
queryset = User.objects.all()
serializer_class = UserSerializer
class SnippetList(generics.ListCreateAPIView):
permission_classes = [permissions.IsAuthenticatedOrReadOnly]
queryset = Snippet.objects.all()
serializer_class = SnippetSerializer
def perform_create(self, serializer):
serializer.save(owner=self.request.user)
class SnippetDetail(generics.RetrieveDestroyAPIView):
# detail 所有人都能讀,但是只有擁有者可以更改
# permissions.IsAuthenticatedOrReadOnly 表示沒有認證的人有讀的權限,認證的人有所有權限
# IsOwnerOrReadOnly 通過了前面的授權之后,還要通過這個授權
# 當所有的授權都通過的時候 所有的對象實例都返回true 表示授權通過
permission_classes = [permissions.IsAuthenticatedOrReadOnly, IsOwnerOrReadOnly]
queryset = Snippet.objects.all()
serializer_class = SnippetSerializer
總結:通過傳遞permission_classes 類變量 傳遞授權類,
1、請求要進行某個操作的時候 ->
2、傳遞參數將授權類列表中的多個授權類實例化得到實例化對象->
3、調用所有授權實例對象的has_、permission以及has_object_permission方法 ->
4、所有的返回結果都為true ->
5、該操作的授權才通過,數據操作向下繼續(xù)進行。
以上這篇Django REST framwork的權限驗證實例就是小編分享給大家的全部內容了,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關文章
pytorch環(huán)境配置及安裝圖文詳解(包括anaconda的安裝)
這篇文章主要介紹了pytorch環(huán)境配置及安裝圖文詳解(包括anaconda的安裝),本文給大家介紹的非常詳細,對大家的學習或工作具有一定的參考借鑒價值,需要的朋友可以參考下2023-04-04
python使用numpy尋找二維數組的最值及其下標方法分析
這篇文章主要為大家介紹了python使用numpy尋找二維數組的最值及其下標實現(xiàn)方法詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪2023-08-08
Pytorch中Softmax和LogSoftmax的使用詳解
這篇文章主要介紹了Pytorch中Softmax和LogSoftmax的使用詳解,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2021-06-06
使用sklearn之LabelEncoder將Label標準化的方法
今天小編就為大家分享一篇使用sklearn之LabelEncoder將Label標準化的方法,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2018-07-07

