Python-based Django rest_Framework framework authentication source code analysis,

Source: Internet
Author: User

Python-based Django rest_Framework framework authentication source code analysis,

#! /Usr/bin/env python #-*-coding: UTF-8-*-from rest_framework.views import APIViewfrom rest_framework.response import Responseclass TestView (APIView): def get (self, request, * args, ** kwargs): # self. dispatch print (request. user) print (request. auth) return Response ('get request, Response content') def post (self, request, * args, ** kwargs): return Response ('Post request, Response content ') def put (self, request, * args, ** kwargs): return Response ('put request, Response content ')

At the beginning of the above request, do not execute the self-written method, such as: (get, post, put), it will first execute the dispach method, if not, go back to its parent class.

Execute dispach of its parent class

Django rest framework process:

It was inherited when CBV was used.From django. views the views method in the import View. Write the get and post methods such as class HostView (view)

If Django rest Framework is available, it does not need to be inherited.From django. views import View's views method,:

Pilot import:From rest_framework.views import APIView, which inheritsAPIView, which does not inherit django views, such:Class AuthView (APIView ):


From rest_framework.views import APIViewImport to APIView
from django.shortcuts import render,HttpResponse
Class AuthView (APIView ):Inherit from APIViewAuthentication_classes = [] def get (self, request): return Response ('....')

In class AuthView (APIView ),APIViewIt inherits the view, such:

Click view To Go To The django view. This view is the one in the previous CBV, for example:

 

 

The inherited analogy is that this class of django has more features than that of django, and its nature is the same as that of the original one. Execute dispatch first and then execute its own, if no, the parent class is executed. If the parent class does not, the original dispatch is executed..

Although it was the same in nature before, it has changed now. Now its request is a request in rest_framework, and the original request is a request in django, for example:

Class HostView (APIView): def get (self, request, * args, ** kwargs): # the original request object, django. core. handlers. wsgi. WSGIRequest # the current request object, rest_framework.request.Request \ self. dispatchExecute dispatch before the request comes in.Print (request. user) print (request. auth) return Response ('host list ')

1. Execute dispatch before the request comes in, while dispatch is in APIView. dispatch is in it and runs itself first, if you delete it first, the default one is provided by django, for example:

 

The source code of the request is as follows:

The first step of source code:

 

Def dispatch (self, request, * args, ** kwargs ):Execute dispatch before the request comes in."""'. Dispatch () 'is pretty much the same as Django's regular dispatch, but with extra hooks for startup, finalize, and exception handling. "self. args = argsDispatch first obtains the ParameterSelf. kwargs = kwargs
#1. process the request
'''
The first step in source code 1,In the request object (it is much more encapsulated than the original class ):
Request,
Parsers = self. get_parsers (),
Authenticators = self. get_authenticators (), where the objects of the two columns are stored.
Negotiator = self. get_content_negotiator (),
Parser_context = parser_context
'''Request = self. initialize_request (request, * args, ** kwargs)This method is executed here, And it returns the requestSelf. request = request self. headers = self. default_response_headers # deprecate? Try:
Step 2: 2Self. initial (request, * args, ** kwargs) # Get the appropriate handler method if request. method. lower () in self. http_method_names:
# Execute reflection hereHandler = getattr (self, request. method. lower (), self. http_method_not_allowed) else:
# Obtain results after reflectionHandler = self. http_method_not_allowedStep 3:3. Execute functions such as get/post/delete/put.Response = handler (request, * args, ** kwargs)Returned resultsFailed t Exception as exc: response = self. handle_exception (exc)Step 4: 4. reprocess the returned resultsSelf. response = self. finalize_response (request, response, * args, ** kwargs) return self. response

 

In execution Request = self. when initialize_request (request, * args, ** kwargs) is performed, you can find the parent class first, but not the parent class, for example:

If there is no static field above, take it as follows:

The request is processed during execution, for example:

 

Step 2 of source code execution:

Def initial (self, request, * args, ** kwargs): "" Runs anything that needs to occur prior to calling the method handler. "self. format_kwarg = self. get_format_suffix (** kwargs) # Perform content negotiation and store the accepted info on the request neg = self. required m_content_negotiation (request) request. accepted_renderer, request. accepted_media_type = neg # Determine the API version, if versioning is in use.
2.1 process version informationVersion, scheme = self. determine_version (request, * args, ** kwargs) request. version, request. versioning_scheme = version, scheme # Ensure that the incoming request is permitted
2.2 authentication and authorizationSelf. Authentication m_authentication (request)
2.3 permission VerificationSelf. check_permissions (request)
2.4 request the user to limit the Access FrequencySelf. check_throttles (request)

Perform the 2.2 authentication and authorization in step 2 of the source code:

Def initial (self, request, * args, ** kwargs): "" Runs anything that needs to occur prior to calling the method handler. "self. format_kwarg = self. get_format_suffix (** kwargs) # Perform content negotiation and store the accepted info on the request neg = self. required m_content_negotiation (request) request. accepted_renderer, request. accepted_media_type = neg # Determine the API version, if versioning is in use. version, scheme = self. determine_version (request, * args, ** kwargs) request. version, request. versioning_scheme = version, scheme # Ensure that the incoming request is permitted self. perform_authentication (request)To execute this step, click as shown in the following figure:Self. check_permissions (request) self. check_throttles (request)
Find your own, and do not execute the following:
Def authentication m_authentication (self, request): "" Perform authentication on the incoming request. note that if you override this and simply 'pass', then authentication will instead be stored med lazily, the first time either 'request. user 'or 'request. auth 'is accessed. "request. userHere, the request is a transfer request, not the original request.

Next, it will find the user, for example:

Find user:

Def user (self): "Returns the user associated with the current request, as authenticated by the authentication classes provided to the request. "if not hasattr (self, '_ user '):If no user existsSelf. _ authenticate ()This lineSelf. _ authenticate () method, find this method
return self._user
Def _ authenticate (self): "Attempt to authenticate the request using each authentication instance in turn ."""
Loop Object ListFor authenticator in self. authenticators:Here, authenticators is the object list, which loops through this object listTry:
Execute the authenticate Method for each objectUser_auth_tuple = authenticator. authenticate (self)Here it returns two valuesExcept t exceptions. APIException:If no verification is successful, an error is reported.Self. _ not_authenticated () raise if user_auth_tuple is not None: self. _ authenticator = authenticator self. user, self. auth = user_auth_tupleHere self. auth, self. user will have a value, and the verification will passReturn self. _ not_authenticated ()

 

 

 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.