日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

Restful framework【第七篇】权限组件

發布時間:2025/3/14 编程问答 18 豆豆
生活随笔 收集整理的這篇文章主要介紹了 Restful framework【第七篇】权限组件 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

基本使用

-寫一個類: class MyPer(BasePermission):message='您沒有權限'def has_permission(self, request, view):# 取出當前登錄用戶user = request.user# 取出當前登錄用戶類型的中文tt = user.get_user_type_display()if user.user_type == 0:return Trueelse:return False -局部使用permission_classes=[MyPer] -全局使用在setting中"DEFAULT_PERMISSION_CLASSES":['app01.auth.MyPer'],

添加權限

(1)API/utils文件夾下新建premission.py文件,代碼如下:

  • message是當沒有權限時,提示的信息
# utils/permission.pyclass SVIPPremission(object):message = "必須是SVIP才能訪問"def has_permission(self,request,view):if request.user.user_type != 3:return Falsereturn Trueclass MyPremission(object):def has_permission(self,request,view):if request.user.user_type == 3:return Falsereturn True

(2)settings.py全局配置權限

#全局 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,]? ?#局部使用權限方法
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,MyPremissionORDER_DICT = {1:{'name':'apple','price':15},2:{'name':'dog','price':100} }def md5(user):import hashlibimport 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'] = 1001ret['msg'] = '用戶名或密碼錯誤'#為用戶創建tokentoken = md5(user)#存在就更新,不存在就創建models.UserToken.objects.update_or_create(user=obj,defaults={'token':token})ret['token'] = tokenexcept Exception as e:ret['code'] = 1002ret['msg'] = '請求異常'return JsonResponse(ret)class OrderView(APIView):'''訂單相關業務(只有SVIP用戶才能看)'''def get(self,request,*args,**kwargs):self.dispatch#request.user#request.authret = {'code':1000,'msg':None,'data':None}try:ret['data'] = ORDER_DICTexcept Exception as e:passreturn JsonResponse(ret)class UserInfoView(APIView):'''訂單相關業務(普通用戶和VIP用戶可以看)'''permission_classes = [MyPremission,] #不用全局的權限配置的話,這里就要寫自己的局部權限def get(self,request,*args,**kwargs):print(request.user)return HttpResponse('用戶信息')

urls.py

from django.contrib import admin from django.urls import path from API.views import AuthView,OrderView,UserInfoViewurlpatterns = [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()), ] 

auth.py

# API/utils/auth/pyfrom rest_framework import exceptions from API import models from rest_framework.authentication import BaseAuthenticationclass 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,提示沒有權限

?

?普通用戶訪問UserInfoView,可以返回信息

?權限源碼流程

(1)dispatch

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 = argsself.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.封裝requestrequest = self.initialize_request(request, *args, **kwargs)self.request = requestself.headers = self.default_response_headers # deprecate?try:#2.認證self.initial(request, *args, **kwargs)# Get the appropriate handler methodif 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_allowedresponse = 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

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 requestneg = 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這個就是我們自己寫的權限判斷

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

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

?

?所以settings全局配置就如下

#全局 REST_FRAMEWORK = {"DEFAULT_PERMISSION_CLASSES":['API.utils.permission.SVIPPremission'], }

內置權限

django-rest-framework內置權限BasePermission

默認是沒有限制權限

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 Truedef has_object_permission(self, request, view, obj):"""Return `True` if permission is granted, `False` otherwise."""return True

我們自己寫的權限類,應該去繼承BasePermission,修改之前寫的permission.py文件

# utils/permission.pyfrom rest_framework.permissions import BasePermissionclass SVIPPremission(BasePermission):message = "必須是SVIP才能訪問"def has_permission(self,request,view):if request.user.user_type != 3:return Falsereturn Trueclass MyPremission(BasePermission):def has_permission(self,request,view):if request.user.user_type == 3:return Falsereturn True

總結:

(1)使用

  • 自己寫的權限類:1.必須繼承BasePermission類;? 2.必須實現:has_permission方法

(2)返回值

  • True? ?有權訪問
  • False? 無權訪問

(3)局部

  • permission_classes = [MyPremission,]?

?(4)全局

REST_FRAMEWORK = {#權限"DEFAULT_PERMISSION_CLASSES":['API.utils.permission.SVIPPremission'], }

?

轉載于:https://www.cnblogs.com/596014054-yangdongsheng/p/10402986.html

與50位技術專家面對面20年技術見證,附贈技術全景圖

總結

以上是生活随笔為你收集整理的Restful framework【第七篇】权限组件的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。