zoukankan      html  css  js  c++  java
  • restframework的认证

    有时我们的页面需要登录后才能查看,这时候就需要用到我们的认证组件

    简单的写法:

    from rest_framework.exceptions import AuthenticationFailed
    from rest_framework.authentication import BaseAuthentication
    
    class MyAuth(BaseAuthentication): def authenticate(self,request): # 写一些认证的逻辑 # print('认证类中的方法,只要配置了就会走') token = request.Get.get('token') token_obj = models.Token.objects.filter(token=token).first() if token_obj: # 没有值表示没有登录 return token_obj.user,token_obj else: raise AuthenticationFailed('您没有登录')

    class Books(APIView): authentication_classes=[MyAuth,] def get(self,request): return Response()

    .一般我们会单独写一个py文件,然后通过导入的方法

    我们还可以设置全局和局部的认证

    # 局部使用
        authentication_classes=[MyAuth,]
    
    # 全局使用
        settings.py中写
        REST_FRAMEWORK={
            "DEFAULT_AUTHENTICATION_CLASSES":["app01.service.auth.Authentication",]
        }

    但是登录页面的话我们使用全局认证的话我们就进不去,所以还有局部禁用

    只需要在不需要认证的类里加上这个命令就不会进行认证了

        # 局部禁用
        authentication_classes=[]
  • 相关阅读:
    钟国晨160809323(作业5)
    12
    11
    第九次
    8作业
    第七次作业
    6
    林昊5
    计算机网络原理与应用笔记 3/29
    计算机网络原理与应用笔记 3/22
  • 原文地址:https://www.cnblogs.com/tuzaizi/p/13485311.html
Copyright © 2011-2022 走看看