美文网首页
Django drf 认证基本流程

Django drf 认证基本流程

作者: Ginta | 来源:发表于2019-02-20 20:33 被阅读0次

    源码流程

    image.png
    1. 首先执行dispatch方法
    2. 重新封装Request
    3. initial(request)方法里面有各种封装函数
    4. 其中perform_authentication(request)是认证的函数
    5. 返回一个request.user
    6. def _authenticate():循环所有的authentication对象,执行authenticate方法
    7. Authtication 自定义认证类
      def authenticate():
      自定义认证
      -报错
      -返回元组(request.user, request.auth)

    使用

    1. 定义一个认证类,实现authenticate方法
    from rest_framework.authentication import BaseAuthentication
    class FirstAuthtication(BaseAuthentication):
        def authenticate(self, request, *args, **kwargs):
            pass
    
        def authenticate_header(self, request):
            pass
    
    1. 返回值
    • 返回None, 执行下一个认证
    • 有返回值,返回一个元组,第一个参数存在request.user里,第二个在request.auth里
    • 异常
    from rest_framework import exceptions
    raise exceptions.AuthenticationFailed('用户认证失败')
    
    1. 局部使用
      相关业务
    from rest_framework.views import APIView
    class UserInfoView(APIView):
        authentication_classes = []
        def get(self, request, *args, **kwargs):
            print(request.user)
            return HttpResponse('用户相关信息')
    
    1. 全局使用
    REST_FRAMEWORK = {
        # 'DEFAULT_AUTHENTICATION_CLASSES': ['apps.api.utils.auth.FirstAuthtication', 'apps.api.utils.auth.Authtication'],
        'DEFAULT_AUTHENTICATION_CLASSES': ['apps.api.utils.auth.Authtication'],
        'UNAUTHENTICATED_USER': None,
        'UNAUTHENTICATED_TOKEN': None,
    }
    

    相关文章

      网友评论

          本文标题:Django drf 认证基本流程

          本文链接:https://www.haomeiwen.com/subject/udjkyqtx.html