返回顶部

DRF之权限

一. DRF权限

我们看过源码已经知道了,认证完了后,就开始权限的校验。

表结构:

from django.db import models

# Create your models here.

class UserInfo(models.Model):

    username = models.CharField(verbose_name='用户名', max_length=32)
    password = models.CharField(verbose_name='密码', max_length=32)
    type_choice = ((1, "VIP"), (2, "SVIP"), (3, "SSVIP"))
    user_type = models.IntegerField(choices=type_choice, null=True, blank=True)


class UserToken(models.Model):
    user = models.OneToOneField('UserInfo', on_delete=models.CASCADE)
    token = models.CharField(verbose_name='token值', max_length=64)

做了一层路由分发:

path('auth/', include('authDemo.urls'))

urls:

from django.urls import path

from authDemo.views import DemoView,AuthDemo,TestView

urlpatterns = [

    path('', DemoView.as_view()),
    path('login', AuthDemo.as_view()),
    path('test', TestView.as_view())

]

 

1.简单应用

自定义一个权限类,继承于  BasePermission

from rest_framework.permissions import BasePermission



class MyPermission(BasePermission):

    message = '权限不够!'
    def has_permission(self, request, view):
        if request.user.user_type >= 2:
            return True
        return False

局部应用

然后在我们的视图中应用:

class TestView(APIView):

    authentication_classes = [MyAuth,]
    permission_classes = [MyPermission, ]

    def get(self, request):
        print(request.user)
        print(request.auth)
        # user_id = request.user.id

        return Response("认证测试")

测试:

 

 

 

 

 

 

全局应用

REST_FRAMEWORK={
    "DEFAULT_AUTHENTICATION_CLASSES": ["utils.auth.MyAuth"]
  "DEFAULT_PERMISSION_CLASSES":["utils.permission.Mypermission",]
}

 

posted @ 2020-10-14 21:14  muguangrui  阅读(93)  评论(0编辑  收藏  举报