• Django -- DRF 认证流程


    Django Restful Framework (DRF)中类的调用与自定义-- 以 autentication 认证为例


    DRF 的 request 对 django 的 request 进行了更一步的封装; 通过获取认证相关的所有类,并实例化,传入request对象(user,auth)


    自定义实例

    from django.shortcuts import render
    from rest_framework.views import APIView
    from rest_framework.response import Response
    from rest_framework.request import Request
    from goods.serializers import GoodsSerializer
    from rest_framework.exceptions import APIException
    # Create your views here.
    from goods.models import Goods
    
    class MyAuthentication(object):
        def authenticate(self,request):
            token = request.query_params.get('token')
            if token == 'abc':
                return ('aaa','bbb')
            raise APIException('认证失败')
    
    
    class GoodsListView(APIView):
        authentication_classes = [MyAuthentication,]
        def get(self,request,*args,**kwargs):
            print(request.user,request.auth)
            goods = Goods.objects.all()
            goods_serializer = GoodsSerializer(goods,many=True)
            return Response(goods_serializer.data)
    

    流程


    在使用的时候 使用 BaseAuthentication类


    这里可以把认证 当成用户登录状态的判断

    登录时不需要 认证,登录之后的访问都需要 进行 登录用户身份的确认。
    
    可以全局添加认证,然后把登录,或者主页等不需要 登录的视图,设置为 authentication_classes= []
    

    当 authenticate 不处理返回None的时候,匿名用户的设置

    REST_FRAMEWORK = {
        "DEFAULT_AUTHENTICATION_CLASSES":[],
        # "UNAUTHENTICATED_USER":lambda :'匿名用户',
        "UNAUTHENTICATED_USER":None,
        # "UNAUTHENTICATED_TOKEN":lambda :'没有验证信息',
        "UNAUTHENTICATED_TOKEN":None,
    
    }
    

    BasicAuthentication

        def authenticate_header(self, request):
            return 'Basic realm="%s"' % 'api
    

  • 相关阅读:
    python libsvm模块在mac上的安装
    logistic regression (Python&Matlab实现)
    读C++ primer 的一些练习
    R笔记
    python学习笔记
    linux常用命令
    macbook air安装ubuntu双系统简记
    解方程——对分法
    解方程——不动点迭代
    隐马尔可夫模型模型评估及最优路径的matlab实现
  • 原文地址:https://www.cnblogs.com/big-handsome-guy/p/8485330.html
Copyright © 2020-2023  润新知