• 五 .Django---framework框架 权限组件


    一 . 权限组件

    https://www.cnblogs.com/pythonywy/p/11492877.html     drf框架中认证与权限工作原理及设置

    
    
    from rest_framework.views import APIView  源码中
     self.check_permissions(request)    # 权限组件      必须是    



    def has_permission
    ():
    pass
    
    

    1.局部权限组件

    model

    from
    django.db import models # Create your models here. class User(models.Model): name=models.CharField(max_length=32) pwd=models.CharField(max_length=32) type_choices=((1,"普通用户"),(2,"VIP"),(3,"SVIP")) user_type=models.IntegerField(choices=type_choices,default=1) class Token(models.Model): user=models.OneToOneField("User") token = models.CharField(max_length=128) def __str__(self): return self.token class Book(models.Model): title=models.CharField(max_length=32) price=models.IntegerField() pub_date=models.DateField() publish=models.ForeignKey("Publish") authors=models.ManyToManyField("Author") def __str__(self): return self.title class Publish(models.Model): name=models.CharField(max_length=32) email=models.EmailField() def __str__(self): return self.name class Author(models.Model): name=models.CharField(max_length=32) age=models.IntegerField() def __str__(self): return self.name
    viwes
    from django.shortcuts import render, HttpResponse from django.views import View from rest_framework.response import Response from .models import * from rest_framework.views import APIView from rest_framework import exceptions from rest_framework.authentication import BaseAuthentication from .models import * # 序列化 class BookModelSerializers(serializers.ModelSerializer): class Meta: model = Book fields = "__all__" # # publish=serializers.CharField(source="publish.pk") # publish = serializers.HyperlinkedIdentityField( # view_name="detailpublish", # lookup_field="publish_id", # lookup_url_kwarg="pk", # # ) # 认证组件 class TokenAuth(BaseAuthentication): def authenticate(self, request): token = request.GET.get("token") token_obj = Token.objects.filter(token=token).first() if not token_obj: raise exceptions.AuthenticationFailed("验证失败!") else: return token_obj.user.name, token_obj.token # 权限组件 class SVIPPermission(object): message = "只有超级用户才能访问" def has_permission(self, request, view): username = request.user user_type = User.objects.filter(name=username).first().user_type if user_type == 3: return True # 通过权限认证 else: return False class BookView(APIView): authentication_classes = [TokenAuth,] # [TokenAuth(),] 认证组件局部 permission_classes = [SVIPPermission,] # 权限组件局部 # throttle_classes = [] def get(self, request): print("request.user", request.user) print("request.auth", request.auth) print("_request.body", request._request.body) print("_request.GET", request._request.GET) book_list = Book.objects.all() bs = BookModelSerializers(books_page, many=True, context={'request': request}) return Response(bs.data)
       url(r'^books/$', views.BookView.as_view(),name="books"),

     2.全局权限组件

    utils.py

    from
    rest_framework import exceptions from rest_framework.authentication import BaseAuthentication from .models import * # 认证组件 class TokenAuth(BaseAuthentication): def authenticate(self,request): token = request.GET.get("token") token_obj = Token.objects.filter(token=token).first() if not token_obj: raise exceptions.AuthenticationFailed("验证失败!") else: return token_obj.user.name,token_obj.token # 权限组件 class SVIPPermission(object): message="只有超级用户才能访问" def has_permission(self,request,view): username=request.user user_type=User.objects.filter(name=username).first().user_type if user_type==3: return True # 通过权限认证 else: return False
    settings.py配置如下:

    REST_FRAMEWORK = { "DEFAULT_AUTHENTICATION_CLASSES": ["myapp.utils.TokenAuth",], "DEFAULT_PERMISSION_CLASSES": ["myapp.utils.SVIPPermission",], }
    在app01.service.permissions.py中:
    
    from rest_framework.permissions import BasePermission
    class SVIPPermission(BasePermission):
        message="SVIP才能访问!"
        def has_permission(self, request, view):
            if request.user.user_type==3:
                return True
            return False
    
    views.py:
    from app01.service.permissions import * class BookViewSet(generics.ListCreateAPIView): permission_classes = [SVIPPermission,] queryset = Book.objects.all() serializer_class = BookSerializers
    全局视图权限 settings.py配置如下: REST_FRAMEWORK
    ={ "DEFAULT_AUTHENTICATION_CLASSES":["app01.service.auth.Authentication",], "DEFAULT_PERMISSION_CLASSES":["app01.service.permissions.SVIPPermission",] }
  • 相关阅读:
    前端开发笔记(2)css基础(上)
    前端开发笔记(1)html基础
    <Android 基础(三 十)> Fragment (3) ~ PreferenceFragment
    MyEclipse中搭建Struts2开发环境
    Android 投射工具和录屏工具
    似是而非的k=sqrt(n)
    算法:求比指定数大且最小的“不重复数”问题的高效实现
    巧用“异或”
    12个滑稽的C语言面试问答——《12个有趣的C语言问答》评析(5)
    12个滑稽的C语言面试问答——《12个有趣的C语言问答》评析(4)
  • 原文地址:https://www.cnblogs.com/lovershowtime/p/11651675.html
Copyright © 2020-2023  润新知