permissions
This is the 24th day of my participation in the August Text Challenge.More challenges in August
Thank you for meeting you. I’m Y Dazhuang
By Y Dazhuang Link: juejin.cn/user/756923… The copyright belongs to the author. Commercial reprint please contact the author for authorization, non-commercial reprint please indicate the source.
🌊🌈
Part of the article and pictures from the Internet, if you have any questions please contact me
🌊🌈
1. Custom implementation (basic use) :
When we define a user model class, we usually define a user type, and permissions are roughly implemented according to the user type
Write permission class that returns True,False(True for access) by getting the user type of the database
# app02.utils.permission.py
class Mypermission(object) :
""" "Administrator """
def has_permission(self, request, value) :
if request.user.user_type == 2:
return True
return False
class Mypermission01(object) :
""" Ordinary user management users can access """
def has_permission(self, request, value) :
ifrequest.user.user_type ! =2:
return True
return True
Copy the code
# use
from .utils.permission import Mypermission01,Mypermission
class OrderView(APIView) :
permission_classes = [Mypermission01, ]
def get(self, request, *args, **kwargs) :
ret = {'code': 200.'message': 'ok! '.'data': None} Set the message to be returned
try:
ret['data'] = ORDER_DICT
except Exception as e:
ret['code'] = 1001
ret['message'] = 'Server not found'
return JsonResponse(ret)
Copy the code
Set your own message to return, or you can use Response directly
2. Principle of permission flow
-
Under the APIView dispatch
def dispatch(self, request, *args, **kwargs) : Copy the code
-
Self. Initial (request, *args, **kwargs) : authentication method
def initial(self, request, *args, **kwargs) :
# implement authentication
self.perform_authentication(request)
# Permission judgment
self.check_permissions(request)
self.check_throttles(request)
Copy the code
-
Self.check_permissions (request): checks permissions
def check_permissions(self, request) : # self.get_permissions(); for permission in self.get_permissions(): # check whether has_permission returns True or False if not permission.has_permission(request, self): # Error message if the code inside it does not have permission self.permission_denied( request, message=getattr(permission, 'message'.None), code=getattr(permission, 'code'.None))Copy the code
3. Customize global & local permissions
Global permission
-
Write permission authentication class
# app02.utils.permission.py class Mypermission(object) : """ "Administrator """ message = 'You don't have access.' code = '1001' def has_permission(self, request, value) : if request.user.user_type == 2: return True return False class Mypermission01(object) : """ Ordinary user management users can access """ def has_permission(self, request, value) : ifrequest.user.user_type ! =2: return True return True Copy the code
-
In the Settings. Py configuration
REST_FRAMEWORK = { 'DEFAULT_AUTHENTICATION_CLASSES': ['app02.utils.auth.Authtication'.'app02.utils.auth.FirstAuthtication',].# certification # 'DEFAULT_AUTHENTICATION_CLASSES: [' app02. Utils. Auth. FirstAuthtication'], # anonymous users (because we didn't write anything when packaging, let it return None) # 'UNAUTHENTICATED_USER': lambda: 'anonymous user ', 'UNAUTHENTICATED_USER': None.'UNAUTHENTICATED_TOKEN': None.'DEFAULT_PERMISSION_CLASSES': ['app02.utils.permission.Mypermission'] # Admin only access (permissions) } Copy the code
-
use
View functions can change permissions if you don't want to use direct permission_classes = []Copy the code
The local authority
It’s the same as PI (1) up here
from .utils.permission import Mypermission01,Mypermission
class OrderView(APIView) :
permission_classes = [Mypermission01, ] # local
def get(self, request, *args, **kwargs) :
ret = {'code': 1000.'message': 'ok! '.'data': None}
try:
ret['data'] = ORDER_DICT
except Exception as e:
ret['code'] = 1001
ret['message'] = 'Server not found'
return JsonResponse(ret)
Copy the code
4, Permissions
Permission controls can limit user access to views and specific data objects.
- A view access judgment is made before executing the view’s Dispatch () method
- When a specific object is obtained through get_object(), object access permissions are determined
-
Configure it in settings.py
You can set the default permission management class in the configuration file, such as REST_FRAMEWORK = { 'DEFAULT_PERMISSION_CLASSES': ( 'rest_framework.permissions.IsAuthenticated')},# If not specified, the following default configuration is used 'DEFAULT_PERMISSION_CLASSES': ( 'rest_framework.permissions.AllowAny'.)Copy the code
-
Set via the permission_classes property in the view
from rest_framework.permissions import IsAuthenticated from rest_framework.views import APIView class ExampleView(APIView) : permission_classes = (IsAuthenticated,) Copy the code
-
More permissions
# Permission providedAllowAny allow all users to IsAuthenticated IsAdminUser only authenticated users only administrator user IsAuthenticatedOrReadOnly authentication user can operation completely, otherwise can get readCopy the code
-
The sample
For example,from rest_framework.authentication import SessionAuthentication from rest_framework.permissions import IsAuthenticated from rest_framework.generics import RetrieveAPIView class BookDetailView(RetrieveAPIView) : queryset = BookInfo.objects.all() serializer_class = BookInfoSerializer authentication_classes = [SessionAuthentication] permission_classes = [IsAuthenticated] Copy the code