程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式師世界 >> 編程語言 >  >> 更多編程語言 >> Python

[Wu Sir] Django rest framework source code and actual combat_ Day01 (top)

編輯:Python

 (0) Abstract

# Course link

4 Sky fix django rest framework Source code and actual combat _ Bili, Bili _bilibili

# Course content

(1) Contents summary _ A little

(2) Content review _ A little

(3)django View of CBV Basic use

(4)django View of CBV Source flow

(5)django Interview questions and csrf Add

(6)django View of CBV And solve csrf authentication

(7) Sort out the above _ A little

【 Knowledge points supplement --- Add yourself 】


# How can it be said that you have nothing to wear? , I will share my long robes with you.

(2) Content review _ A little

# (1) Directly above


# (2)Django Of FBV and CBV

                1)FBV Is a function - based view ,  Just like what we usually use .

                2)CBV Is a class based view . Is to inherit django.views Medium View . See the code shown in the figure below . When this class is executed , What is the request from the front end , Class will automatically execute the corresponding methods . such as post request , Then the class will execute post Methods .

                In this case, the routing function should be written as follows , Is to add .as_view() As a routing function , Here are the fixed requirements , Why not? . 

                So the top is a CBV The pattern of .


# (3)postman Falsify a request

                1) It is impossible to design the corresponding form submission for each request , It doesn't make sense . We can use postman This tool is used to forge various requests , To view the data returned from the backend .

                

                2)postman Download and install . Download link :Download Postman | Get Started for Free

// When the download is complete , After we open it directly, it will be installed automatically , And generate shortcuts on the desktop . Open the shortcut at this time , As shown in the following figure . Actually postman With web end , But you need a desktop agent to test local url . 

                3)postman Easy to use . As shown in the figure below , The page after we click the plus sign , Then we also specifically used , Tested post request . The error is reported here because we have not shut down django Medium csrf authentication . You can go straight here settings.py Note the authentication at the middleware in the file .


# (4) List generator , Just give me the code and comments


# (5) object-oriented

                1) encapsulation . In two ways , One aspect is to encapsulate methods of the same class into classes . As shown in the figure below , That is, the corresponding methods of each class , And then encapsulate it . 

               

                 The other is to encapsulate data into objects , That is, we pass data into the class , And then the inside self.a1 = The ginseng a1, That's roughly what it means , For class calls , That is, after we instantiate this class , We can not only use methods of classes , And the data inside .

                2) Just talk about decorators @property, The function of this decorator will be discussed in detail in other data analysis classes , We just need to know , Refer to before defining the function . Then when we call this function , You can do without brackets , Just like calling properties . See the following code block , It is an entry-level understanding .

# -*- coding=utf-8 -*-
# github: night_walkiner
# csdn: Pandizi
class Foo:
def __init__(self):
self.price = 100
# (1) Decorator , It must be written at the beginning , The function name is used for subsequent calls ,
# and @property The decorated function , Must return a value , Then the call is the property call , It is not necessary to add parentheses to the method
# It must be said that , If we want to assign values later , Consider the following code :
"""
class Foo Under the
@property
def price(self,value):
pass
When you call it , If we Foo.price You will be prompted that one parameter is missing ,
And if we do Foo.price(100) , Still report a mistake ,
So we need to use the settings required by the decorator , That is, set the value in the following way
"""
@property
def price(self):
return print(" Decorator ")
# If in the future we want to price If you assign a value , Must be decorated price.setter ,
# Observe carefully !!!
@price.setter
def price(self, value):
self.price = value
# This is the same , Also to use (1) As defined in price Come on .deleter As a decoration
@price.deleter
def price(self):
del self.price

                Let's take a look at the last example , It's Wu sir Written code , I won't repeat it . This is also an extension of the encapsulated instance , It's simple . If you encounter a problem, repeat it , Or study it , Let's not go into details .


(3)django View of CBV Basic use

# (1) Detailed content

                1) About CBV Structure of development . in fact HTTP The request is essentially a bunch of strings , adopt /r Separating . But how do we handle requests ? Django Reflection is used in the source code , That is to say getattr() Method to do . If you don't use reflection , We're going to use request.method Go to judge and execute one by one .( Basically all support CBV Structural frameworks are implemented using reflection )

                2) about CBV for , When we use this model , In fact, it is at the routing address , Yes as_view() Methods , Then we can see as_view() Source code , You can see that no matter what request is executed , To perform all self.dispatch() 

                 

                3)self.dispatch The source code is as follows , First, we will get request.method The request for becomes lowercase , For example, the original is GET become get, Then determine whether the request is in   self.http_method_names Inside , This self.http_method_names There are respective request types , Such as post,put wait . getattr(x, "y") amount to x.y It means , Similar property calls .

                4)CBV The specific process of

                5) The execution order of the methods of the parent and child classes . See the code shown in the figure below :

                 As shown in the figure below , For example, at present post request , Then we did dispatch Method .

                First of all : Then the system will find out from the subclass dispatch , The subclass will go to the parent class to find the parent class dispatch, however self It refers to a subclass , After reflection, we find post request ,

                second :  Then call... From a subclass post Method , Return the result to the parent class dispatch, Of the parent class dispatch And then return to the subclass dispatch , And then back to the user .


(4)django View of CBV Source flow ( Better think more , What the teacher said is not very clear )

# (1)CBV Supplement to the source code process . I believe this area will become more solid with in-depth study , And have a better understanding .


# (2) Inherit


(5)django Interview questions and csrf Add

# (1)Django middleware

                1)Django The middleware can only write at most 5 A way , It is the following figure . I used to say process_request() and process_response() The two methods are the most commonly used .

                 among process_exception() The method is to execute only when there is an exception , No exceptions, no execution . about process_render_template() Method , If the view function returns render() Will execute this middleware , Otherwise execution HttpResponse() The words will never be carried out .

                

               

                2) The execution process of middleware _(Django 1.10 Version above ), See figure below , Let's briefly describe the execution process of middleware , When asked to come in :

                First of all : The first is to execute all Middleware in sequence process_request() Method , And then route matching , But do not execute the view function ;

                second : After route matching , Return to the first layer of middleware , Continue to execute their... In sequence process_view() Method , The view function is not executed until it is finished ;

                Third : The view function executes and returns correctly (HttpResponse) When , We'll start process_response() Method to return to the browser .

                Fourth : if , An error occurred while executing the routing function , Then it will carry out process_exception() Method returns an exception ;

                The fifth : if , The view function executes correctly , But back render() Then execute the middleware process_render_template() Method , And then back to the browser .

【 Fourth 、 The fifth part is shown in the following figure .】

                3) What can you do with middleware ? The commonly used ones are authority authentication and user login authentication .


# (2)csrf Certified interview questions

                1)Django Middleware in  csrf_token The implementation of the .csrf The middleware of is written in process_view() Method .【 See behind (3) Of 3) Explanation 】


# (3) exempt csrf Certified trimmers and individual csrf Certified trimmer

                1) Suppose we add all the global view functions csrf authentication , That is to say, in the place of middleware csrf Open Authentication , So if we want to exempt a view function from csrf You can use the decorator exempted from certification after certification . Then the imported module statement is :from django.views.decorators.csrf import csrf_exempt

As shown in the figure below , So we are in the view function  users The former quoted @csrf_exempt Is to exempt this function csrf Certified . 

                2) Scene two , If we annotate the global csrf authentication , I also want to add... To some specific view functions csrf authentication , Then you can use a separate csrf The decorator . The statement of importing module is :from django.views.decorators.csrf import csrf_protect  . The method of use is the same as that of the exempted decorator . As shown in the figure below .

                3) With the above foundation , We know why csrf Your certification needs to be written in process_view() It's in , This is because when performing authentication , You need to retrieve whether the view function is exempt from authentication ( Or with certification ), There is a need for logical judgment . And if it's written in process_request() In the method , There is no route matching information in request process ,csrf No view function found , Also talk about checking whether the view function has a corresponding decorator ! Then , if necessary csrf authentication , Then check whether it meets the requirements csrf_token The rules of


(6)django View of CBV And solve csrf authentication

# (1)CBV How to customize  csrf authentication ( Custom is to exempt or set authentication separately )

                1) What we said earlier is based on FBV To explain csrf The use of decorators . So for CBV To customize csrf If it's certified , Instead of simply adding decorators to functions in a class .【csrf The decorator is csrf_exempt perhaps csrf_protect】

               

                2) The solution is to use   from django.utils.decorators import method_decorator Medium  method_decorator Decorator , This can be true of CBV Structure setting customization csrf For decorators . For example, the first method is the following method ,@method_decorator(csrf_exempt) That is to exempt the view class csrf authentication ( The same is true for individual settings ). In fact, that is @method_decorator(csrf Decorator ), As long as it is in the following format .

class StudentsView(View):
# Custom authentication --- Method 1 , Just put it in dispatch Method front .
# It's official , No why? .
@method_decorator(csrf_exempt)
def dispatch(self, request, *args, **kwargs):
print("before")
# super() It is not simply inherited from the parent class of the current class , Instead, it executes the entire inheritance relationship
# in other words , When looking for a way , First look inside yourself , Could not find take parent class ,
# If the parent class cannot be found again , Go to the second inheritance class
ret = super(StudentsView, self).dispatch(request, *args, **kwargs)
# print(ret)
print("after")
return ret
def get(self, request, *args, **kwargs):
print("get")
return HttpResponse("GET")
# @method_decorator(csrf_exempt) It is useless to add it here !!!
#( That is, it is invalid for individual methods )
# Because the official regulations , Just put it on the dispatch On the way , and dispatch It has to be put in the front .
def post(self, request, *args, **kwargs):
return HttpResponse("POST")
def put(self, request, *args, **kwargs):
return HttpResponse("PUT")
def delete(self, request, *args, **kwargs):
return HttpResponse("DELETE")

               

                3) It can also be the following method , It is placed on the top of the view class , But when it comes to writing, it's just @method_decorator(csrf Decorator ,name="dispatch"). See the following code comments for details .

from django.utils.decorators import method_decorator
from django.views.decorators.csrf import csrf_exempt, csrf_protect
# Custom authentication --- Method 2 , name In fact, it is the method name . Simply put, find this class method , Then add this decorator
@method_decorator(csrf_exempt, name="dispatch")
class StudentsView(View):
def get(self, request, *args, **kwargs):
print("get")
return HttpResponse("GET")
def post(self, request, *args, **kwargs):
return HttpResponse("POST")
def put(self, request, *args, **kwargs):
return HttpResponse("PUT")
def delete(self, request, *args, **kwargs):
return HttpResponse("DELETE")


(7) Sort out the above _ A little

# Directly above


【 Supplementary knowledge 】

# (1)getattr() Use of reflection .

                One more thing to mention is, for example getattr(obj, '_negotiator', None), Is to return to obj._negotiator, If any . We said that before , Without this property , Reflection will report an error , This time you can use the back None 了 , mean , If you don't have this property , The system does not report an error , It's going to return to a None.


# (2) Class inheritance priority



  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式師世界 All Rights Reserved