django配置文件作用,drf 登录功能,drf认证组件,drf权限组件,drf频率组件

发布时间 2023-05-24 20:50:50作者: 秃头不爱学

django配置文件作用:

 

 

 

 drf 登录功能:

  view内:

from .models import UserInfo, UserToken
from rest_framework.viewsets import ViewSet
import uuid
from rest_framework.response import Response
from rest_framework.decorators import action


class UserView(ViewSet):
    @action(methods=['POST'], detail=False)
    def login(self, request):
        # 1.从request.data中拿出数据
        username = request.data.get('username')
        password = request.data.get('password')

        # 2.将拿出的数据在数据库中比对
        user = UserInfo.objects.filter(username=username, password=password).first()

        if user:
            # 3.判断是否正确,如果正确生成随机字符串
            token = str(uuid.uuid4())

            # 4.把随机字符串存到表中
            UserToken.objects.update_or_create(user=user, defaults={'token': token})
            return Response({'code': 100, 'msg': '登录成功', 'token': token})
        else:
            return Response({'code': 101, 'msg': '用户名或密码错误'})

  models内:

class UserInfo(models.Model):
    username = models.CharField(max_length=32)
    password = models.CharField(max_length=32)


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

  url内:

from django.contrib import admin
from django.urls import path,include
from app01 import views
from rest_framework.routers import SimpleRouter

router = SimpleRouter()
router.register('user', views.UserView, 'user')

urlpatterns = [
    path('admin/', admin.site.urls),

    path('login/',include(router.urls))
]

drf认证组件:

  认证组件使用步骤(固定用法):

    1 写一个类,继承BaseAuthentication

    2 在类中写:authenticate

    3.在方法中,完成登录认证,如何不是登录的,抛异常

    4.如果是登录的,返回登录用户和token

      auth中:

from rest_framework.authentication import BaseAuthentication
from .models import UserToken
from rest_framework.exceptions import AuthenticationFailed


class LoginAuth(BaseAuthentication):
    def authenticate(self, request):
        # 校验用户是否登录--------->请求中携带后端给的token,就是登陆了

        # 取出token
        token = request.query_params.get('token')

        # 在数据库中根据token校验有没有数据
        user_token = UserToken.objects.filter(token=token).first()
        if user_token:
            user = user_token.user
            return user, token
        else:
            raise AuthenticationFailed('没有登录不能访问')

      view中:

from rest_framework.views import APIView
from .auth import LoginAuth


class BookView(APIView):
    authentication_classes = [LoginAuth, ]

    def get(self, request):
        return Response({'code': 100, 'msg': '成功', 'data': '很多数据'})

    5 在视图类中,使用认证类(局部使用)
      class BookView(APIView):
      authentication_classes = [LoginAuth, ]
    6 全局使用:
      REST_FRAMEWORK = {
      'DEFAULT_AUTHENTICATION_CLASSES': [
      'app01.auth.LoginAuth'
      ],

      }
    7 全局使用后,局部禁用
      class UserView(ViewSet):
        # 局部禁用
        authentication_classes = [ ]
    8 认证类的使用顺序
      -优先用视图类配置的
      -其次用项目配置文件
      -最后用drf默认的配置

  

drf权限组件:

   权限类的使用步骤
    1 写一个类,继承BasePermission
    2 在类中写方法:has_permission
      -如果有权限,就返回True
      -如果没有权限,就返回False
      -错误信息是self.message='字符串'


    permissions中:

from rest_framework.permissions import BasePermission


class Permissions(BasePermission):
    def has_permission(self, request, view):
        if request.user.user_type == 1:
            print(request.user.user_type)
            return True
        else:
            self.message = '您好,你没有权限'
            return False

    view中:

class BookDetailView(APIView):
    permission_classes = [Permissions]  # 局部禁用

    def delete(self, request, pk):
        return Response({'code': 100, 'msg': '删除成功'})

   setting中:

REST_FRAMEWORK = {
    'DEFAULT_AUTHENTICATION_CLASSES': [
        'app01.auth.LoginAuth'
    ],          # 全局使用认证功能
    'DEFAULT_PERMISSION_CLASSES': [
        'app01.permission .Permissions'
    ],          # 全局使用权限功能
}

    3 局部使用
      class BookDetailView(APIView):
        permission_classes = [AdminPermission, ]
    4 全局使用
      REST_FRAMEWORK = {
      'DEFAULT_PERMISSION_CLASSES': [
      'app01.permission.AdminPermission'
      ],

      }
    5 局部禁用
      class BookView(APIView):
      permission_classes = [ ]

频率组件:

   频率类的使用步骤
    1 写个类,继承:SimpleRateThrottle
    2 重写某个方法:get_cache_key
      -可以返回ip或用户id
      -返回什么,就以什么做频率限制


    throttling中:

from rest_framework.throttling import SimpleRateThrottle


class Mythrottling(SimpleRateThrottle):
    scope = 'lqz'

    def get_cache_key(self, request, view):
        # 返回客户端的ip地址
        ip = request.META.get('REMOTE_ADDR')
        print(ip)
        return ip

    setting中:

REST_FRAMEWORK = {

    'DEFAULT_THROTTLE_RATES': {
        'lqz':'3/m'
    },
}

    3 写一个类属性,随意命名一个名
      scope = 'lqz'
    4 在配置文件中配置:
      'DEFAULT_THROTTLE_RATES': {
      'lqz': '3/m' # 一分钟访问3次
      },

    5 全局用
      'DEFAULT_THROTTLE_CLASSES': [

      ],
    6 局部用
      class BookView(APIView):
      throttle_classes = [MyThrottle]