Look at the source code + user authentication of Django and DRF

How to see the source code of Django and DRF

Principle of CBV

class OrderView(View):
    def get(self, request, *args, **kwargs):
        ret = {
    
    
            'code': 1000,
            'msg': 'xxx'
        }

        return HttpResponse(json.dumps(ret), status=201)

    def post(self, request, *args, **kwargs):
        return HttpResponse('创建订单')

    def put(self, request, *args, **kwargs):
        return HttpResponse('更新订单')

    def delete(self, request, *args, **kwargs):
        return HttpResponse('删除订单')
  • We customize a OrderViewclass that inherits from Viewthe class

  • path('order/',views.OrderView.as_view()),
    
  • The method called in the url , but we did not define it, indicating that this method is inherited OrderViewfromas_view()View

  • so found Viewinas_view()

image-20200830093221565

  • Which clsrefers to our custom OrderView, but selfis the object after instantiation

  • Next jump to dispatchmethod

    image-20200830093802948

  • You can know `If you use the CBV mode in the Django project, you actually call getattr to execute the function corresponding to the request method in the acquisition class

  • Of course, you can also customize dispatchmethods to implement your own operations.

DRF's APIView source code + user authentication

class Myauthentication(object):
    # 用户认证
    def authenticate(self, request):
        token = request._request.GET.get('token')
        # 此处可以获取用户名和密码,进行数据校验
        if not token:
            raise exceptions.AuthenticationFailed('用户认证失败')
        return ('alex', None)
    def authenticate_header(self, val):
        pass

class DogView(APIView):
    # 进行用户认证
    authentication_classes = [Myauthentication, ]
    def get(self, request, *args, **kwargs):
        print(request)
        # 此request和原生的request不同
        # 是DRF的dispatch加工后的request
        print(request.user)
        # 即Myauthentication中的authenticate返回的元组
        self.dispatch
        ret = {
    
    
            'code': 1000,
            'msg': 'xxx'
        }
        return HttpResponse(json.dumps(ret), status=201)

    def post(self, request, *args, **kwargs):
        return HttpResponse('创建Dog')

    def put(self, request, *args, **kwargs):
        return HttpResponse('更新Dog')

    def delete(self, request, *args, **kwargs):
        return HttpResponse('删除Dog')

  • In the same way, according to the urls file, we can find as_view()the method first,

  • If there is no custom one DogView, then go to its parent class, that is APIView,as_view()

  • image-20200830094832187

  • It can be seen that it is the called Viewmethod as_view(), and through the above CBV analysis, it is finally the selfcalled dispatchmethod

  • However, it should be noted that this example selfrefers to our custom DogView, so if you want to find it dispatch, you need to DogViewfind it layer by layer

  • And APIViewthere are dispatchmethods in it, so go to the source code

    image-20200830095817777

  • Original requestprocessed intialize_request, jump to source code

  • image-20200830100806104

  • One item is added authenticators, which is called self.get_authenticators. Similarly, this method also needs to DogViewbe found from the beginning. I did not find it from the parent class.

  • image-20200830101147658

  • Instantiate self.authentication_classesthe class list as an object and continue to jump

  • image-20200830101311037

  • You can DogViewcustomize one in authentication_classes, you can override the default

  • Go back to APIViewthe middle dispatch, find intialthe jump, (the parameter passed in is the processed request)

  • image-20200830101947804

  • continue to jump

    image-20200830102051095

  • Find the processed request( intialize_requestjump from the return value)

  • Set the expansion on the left first

image-20200830102345439

  • image-20200830102427054

  • turn upuser

image-20200830102614040

  • continue to jump

image-20200830102720347

  • Each of them authenticatorhas a authenticatemethod, so we Myauthenticationalso need to write aauthenticate

  • In addition, a authenticate_headermethod is required
    74)]

  • Each of them authenticatorhas a authenticatemethod, so we Myauthenticationalso need to write aauthenticate

  • authenticate_headerIn addition, a method is required

  • In this way, the basic user authentication is realized (the token in the url can be written casually at this time)

Guess you like

Origin blog.csdn.net/jinniulema/article/details/119103523
Recommended