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

歡迎訪問 生活随笔!

生活随笔

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

编程问答

Django中的认证与权限 源码剖析

發布時間:2023/12/20 编程问答 30 豆豆
生活随笔 收集整理的這篇文章主要介紹了 Django中的认证与权限 源码剖析 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

?rest_framework/request.py中部分認證和權限代碼

def _authenticate(self):"""Attempt to authenticate the request using each authentication instancein turn."""for authenticator in self.authenticators:try:user_auth_tuple = authenticator.authenticate(self)except exceptions.APIException:self._not_authenticated()raiseif user_auth_tuple is not None:self._authenticator = authenticatorself.user, self.auth = user_auth_tuplereturnself._not_authenticated()def _not_authenticated(self):"""Set authenticator, user & authtoken representing an unauthenticated request.Defaults are None, AnonymousUser & None."""self._authenticator = Noneif api_settings.UNAUTHENTICATED_USER:self.user = api_settings.UNAUTHENTICATED_USER()else:self.user = None

認證后將user存儲到了request中,為了權限使用時候可以進行判斷(紅色)

class UserLoginPermission(BasePermission):
? ? def has_permission(self, request, view):

? ? ? ? return isinstance(request.user,User)

?

?

?

實例:

authentication.py

from django.core.cache import cache from rest_framework.authentication import BaseAuthenticationclass TokenAuthentication(BaseAuthentication):def authenticate(self, request):token = request.query_params.get("token")user = cache.get(token)if user:return user ,token

permissions.py

from rest_framework.permissions import BasePermissionfrom App.models import Userclass UserLoginPermission(BasePermission):def has_permission(self, request, view):return isinstance(request.user,User)def has_object_permission(self, request, view, obj):if obj.b_author.id == request.user.id:return True

?

?

?

總結

以上是生活随笔為你收集整理的Django中的认证与权限 源码剖析的全部內容,希望文章能夠幫你解決所遇到的問題。

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