Inheritance relationships for classes in Python rest-framework (As_view)

Source: Internet
Author: User

I. BACKGROUND

In recent days have been learning the source code of the RESTful framework, the process of user request, in the routing system this block encountered a question, about the class inheritance relationship, when the request came in to route this block, execute the As_view () method, why run the parent view of the As_view ( ) method to perform the dispatch method to Apiview? I'll record it over here, and I'll check it back.

Two. Code examples

1. Routing

 from Import URL  from Import  = [    url (r'^index/', Api_view. Indexview.as_view ()),]

2. View class

 from Import   Responsefromimport  apiviewclass  Indexview (apiview):     def  Get (self,request):        return Response ('... ')
Three. Source Code Analysis

A. As_view method of Apiview

classApiview (View): @classmethoddefAs_view (CLS, * *Initkwargs):ifIsinstance (GetAttr (CLS,'Queryset', None), Models.query.QuerySet):defforce_evaluation ():RaiseRuntimeError ('Do not evaluate the '. Queryset ' attribute directly,'                    'As the result would be cached and reused between requests.'                    'Use '. All () ' or call '. Get_queryset () ' instead.') Cls.queryset._fetch_all=force_evaluation View= Super (Apiview, CLS). As_view (* *Initkwargs)#here is the method that inherits the parent class As_view ()View.cls=CLS View.initkwargs=InitkwargsreturnCsrf_exempt (view)

# Too much code only intercepts part of the code

B. What do super (APIVIEW,CLS) As_view (**initkwargs) do

# Super (Apiview,self) first finds Apiview's parent class (that is, class View) and then converts the As_view property of the View class to the properties of the class Apiview # equivalent to copying code from view As_view () to As_view in Api_view

So finally run super (APIVIEW,CLS). As_view (**initkwargs) executes the As_view method in view

classView (object): Http_method_names= ['Get','Post','put','Patch','Delete','Head','Options','Trace']    def __init__(Self, * *Kwargs): forKey, ValueinchSix.iteritems (Kwargs): SetAttr (self, key, value) @classonlymethoddefAs_view (CLS, * *Initkwargs): forKeyinchInitkwargs:ifKeyinchCls.http_method_names:RaiseTypeError ("You tried to pass in the %s method name as a"                                "keyword argument to%s (). Don ' t do that."% (key, CLS.__name__))            if  nothasattr (CLS, key):RaiseTypeError ("%s () received an invalid keyword%r. As_view"                                "Only accepts arguments that is already"                                "attributes of the class."% (CLS.__name__, key)) defView (Request, *args, * *Kwargs): self= CLS (* *Initkwargs)ifHasattr (Self,'Get') and  notHasattr (Self,'Head'): Self.head=Self.get self.request=Request Self.args=args Self.kwargs=KwargsreturnSelf.dispatch (Request, *args, * *Kwargs)#run here, and finally execute the Self.dispatch.View.view_class =CLS View.view_initkwargs=Initkwargs update_wrapper (view, CLS, updated=()) Update_wrapper (view, Cls.dispatch, assigned=())        returnView#returns the View function

Inheritance relationships for classes in Python rest-framework (As_view)

Related Article

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.