Django中的认证与权限 源码剖析
生活随笔
收集整理的這篇文章主要介紹了
Django中的认证与权限 源码剖析
小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.
?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 ,tokenpermissions.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中的认证与权限 源码剖析的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Qt/QML离线地图瓦片下载工具(瓦片地
- 下一篇: 项目立项和支付要求