• 五 .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",] }
  • 相关阅读:
    CDS是一个企业级的持续交付和DevOps自动化开源平台
    基于VictoriaMetrics的prometheus 集群监控报警方案
    VictoriaMetrics vmalert 重启状态的处理
    karma prometheus alertmanager dashboard简单试用
    kthxbye一种解决prometheus alertmanager 报警确认的守护进程
    karma 一个不错的prometheus alertmanager dashboard
    inversify 强大&&轻量级的基于typescript 的ioc 框架
    VictoriaMetrics vmagent的一些介绍
    VictoriaMetrics vmalert 说明
    VictoriaMetrics vmauth 说明
  • 原文地址:https://www.cnblogs.com/lovershowtime/p/11651675.html
Copyright © 2020-2023  润新知