decorator, viewsystem 063

decorator, viewsystem 063

The long-awaited decorator is finally here!!!


 

1 decorator

Definition: Without changing the calling method of the original function and adding additional functions to the function

Create a new python file and write in it

Introduction: Define a function to print the execution time when the function is called and executed (introduce the event module)

You can define a time function and pass the function that needs to be executed into the time function. That's it.

Problem: This changes the way the function is called 

import time
 def timer(func):
     def inner():
         print (time.time()) 
        ret = func()    #Original function 
        return ret
     return inner 

def func1():
     print (func1)
     return  ' the return value of func1 ' 
a = timer(func1) #The return value at this time is the return value of inner 
a()
 #The calling method is still changed 
# Use 
the func1 below = timer(func1) 
func1() 
#The calling method will not change in this way 
# Decorator It is an application of closure 
# It can also be used in this way, this is the case of using syntax to use decorators
@timer # Equivalent to func1 = timer(func1)
def func1(): 
    print(func1) 
    return 'the return value of func1'
func1()  

  Closures are used

  example code

#Definition dating function 
# You need to download the software first 
def download(func): # Add function to the function
     def inner():
         print ( ' download software ' ) 
        func() 
    return inner
 #Use different tools about 
# def yue(tools): 
 #    print('Use {} to make an appointment'.format(tools)) 
 # yue = download(yue) 
@download
 def yue(tools):
     print ( ' Use {} to make an appointment ' .format(tools)) 
    
#Original function Carry the parameter     
yue( ' momo ' )   #now it is the inner in the decorator
yue( ' tantan ' ) 
yue( ' Drifting bottle ' )

  How to write a complete decorator

#standard writing 
def wrapper(func):
     def inner(*args,** kwargs):
         #execute the operation before the decorated function 
        ret = func(*args,** kwargs)
         #execute the operation after the decorated function 
        return ret
     return inner 

#decorate the function 
@wrapper
 def func1():
     print ( ' func1 ' ) 
    
func1()

  Advanced content of decorators:

#Control multiple decorators 
# Define a switch 
# Globally define one 
# flag = True 
# if #judgment flag 
import time 
flag = True
 def outer(flag):
     def timer(func):
         def inner(*args,** kwargs)
             if flag:
                 print (time.time()) 
                ret = func(*args,** kwargs)
             else : 
                ret = func(*args,** kwargs)
              return ret
         return inner
    
@outer(True) 
def func1():
     print ( ' func1 ' ) will execute the decorator 
   
@outer(False) 
def func2():
     print ( ' func2 ' ) 
    
func1() 
func2()

  After printing the results, we will find that the func2 function does not print the time, that is, the effect of writing a decorator but not adding a device to func2 is realized.

  Multiple decorators decorate the same function:

# Fixed usage 
def wrapper1(func1):
     def inner(*args,** kwargs):
         print ( ' before wrapper1 ' ) #2 
        ret = func(*args,** kwargs)
         print ( ' after wrapper1 ' ) #5
         return ret
     return inner
 def wrapper2(func2):
     def inner(*args,** kwargs)
         print ( ' before wrapper2 ' ) #1 
        ret = func(*args,** kwargs)
         print( ' after wrapper2 ' ) #4
         return ret
     return inner 
@wrapper2 # func1 = wrapper2(func1) wrapper2.inner 
@wrapper1 # func1 = wrapper1(func1) wrapper1.inner 
#func = func1
def func1(): print ( ' func1 ' ) #3 return ' the return value of func1 ' print( func1()) # 6

# The way of thinking in this way is firstly wrapper1 decorates func1 first, after the decoration, func1 = wrapper(func1), that is,
#func1 at this time is actually of wrapper1 Decorating the inner function is also about decorating the inner function of wrapper1
#that is, func1 = the inner function of wrapper1, so the final display result is to execute the inner function of wrapper2 first and print 'before wrapper2'
#Continue to execute, the function at this time is the inner function of wrapper1, which jumps to wrapper1, prints 'before wrapper1', and then executes
# is the wrapped function in wrapper1, that is, the real func1 prints 'func1' Then go down and print 'after wrapper1' and then return d to
'after wrapper2' After executing the decorator, it will execute its own return value
# After execution, return to itself and then continue

You can use this picture to understand the decoration and display it in order. After each layer is executed, it will return to itself and continue downward.

Decorator Repair Techniques:

#Need to know which function is executed 
# print(func1(__name__)) 

# from functools import wraps 
#Put @wraps(func) on the inner to 
import time
 from functiontools import wraps
 def timer(func): 
    @wraps (func) 
    def inner():
         print (time.time()) 
        ret = func()   #Original function 
        return ret
     return inner 
@timer # func1 = timer(func1) 
def func1():
      """ 
    func1 xxxx 
    :return : 
    """
    print ( ' func1 ' )
     return  ' return value of func1 ' 

@timer   # func1 = timer(func1) 
def func2():
     """ 
    func2 xxxx 
    :return: 
    """ 
    print ( ' func2 ' )
     return  ' return value of func2 ' 

print (func1. __name__ )
 print (func2. __name__ )
 print (func2.__doc__ )   #Adding this line will display the comment of function 2. Adding this item in the log can identify which function is executed and the 
display result is 
func1 
func2

    func2 xxxx
    :return:
2 view system
  1 CBV and FBV

    FBV(function based view)

    CBV(class based view)

  What we have written before are function-based views, called FBV. Views can also be written as class-based.

  Steps to write CBV:

    1 Definition:

#Add Publisher CBV 
from django.views import View 

class AddPublisher(View):
     def get(self, request):
         pass 

    def post(self, request):
         pass

     2 uses:

url(r ' ^add_publishe/ ' , views.AddPublisher.as_view()) # Must have brackets to execute

      3 CBV process:

      1:

views.AddPublisher.as_view() Execute the view function when the program is loaded

       2: Execute the view function when the request comes: 1 self = AddPublisher() 2 self.request = request 3: Execute the self.dispatch method: 1 When judging whether the request method is allowed, obtain the get or defined in AddPublisher through reflection When the post method is not allowed through the handler, self.http_method_not_allowed also gets 2 through the handler. Execute the handler to get the return result HttpResponse object

     4. Add a decorator to CBV

      from django.utils.decorators import method_decorator

      1 Load a get/post method:

@method_decorator(timer)
     def get(self,request): 


# 2 Load the self.dispatch method (recommended usage) 
@method_decorator(timer)
     def dispatch(self,request,*args,** kwargs); 

# 3Add to the class On 
@method_decorator(timer,name= ' post ' )   #There must be a name field to specify which way to add a decorator 
@method_decorator(timer,name= ' get ' )
 class AddPublisher(view):          
 A simple example is as follows
class AddPublisher(View):
      #You can define the method of request yourself 
    # http_method_names = ['get'] 
    @method_decorator(timer)
     def dispatch(self, request, *args, ** kwargs):
         # Operation 
        # start = time.time( ) ret = super(). dispatch 
        (request, *args, ** kwargs)
         # end = time.time() 
        # print('time: {}'.format(end - start)) 
        #operation return 
        ret # @method_decorator (timer) def get(self, request):
         print ( ' get ' )
        

    
    return render(request, 'add_publisher.html')

    # @method_decorator(timer)
    def post(self, request):

        print('post')
        err_msg = ''
        new_name = request.POST.get('new_name')
        if not new_name:
            err_msg = '不能为空'
        obj_list = models.Publisher.objects.filter(name=new_name)
        if obj_list:
            err_msg = '数据已存在'
        if new_name and not obj_list:
            ret = models.Publisher.objects.create(name=new_name)
            return redirect('/publisher_list/')
        return render(request, 'add_publisher.html', {
       
       'err_msg': err_msg, 'new_name': new_name})
    
View Code
 2 request
request.method #Judge the request method 
request.GET   #Get information on the url Similar to a dictionary, you can get it through get() or [] 
request.POST   #Get the POST data submitted on the form 
request.body #Request body request. The data of POST is 
the request.FILES    obtained from the body #A dictionary-like object contains all uploaded file information   
    # Notes 
    # 1. Enctype needs to be added to the form enctype 
    = ' multipart/form-data ' 
    # 2. Add the method Change to post Add name attribute Add {% csrf_token %} 
    method = ' post '   name= ''   {% csrf_token % }
     # 3. Pay attention to the method of setting the file object chunks 


# 上传文件
def upload(request):
    if request.method =='POST':
        file = request.FILES.get('f1')
        with open(file.name, 'wb') as f:
            for chunk in file.chunks():
                f.write(chunk)
        return HttpResponse('上传成功')
    return render(request,'upload.html')

# html页面
<form action="" method="post" enctype="multipart/form-data">
    {
       
       % csrf_token %}
    文件:<input type="file"  name="f1">
    <button>上传</button>
</form>

 

 JsonResponse

JsonResponse is a subclass of HttpResponse designed to generate JSON-encoded responses

from django.http import JsonResponse 

def json_test(request): 
    data = {
       ' name ' : ' dsb ' , ' age ' : ' 12 ' }
     return JsonResponse(data) #The second method manually sets the return value def json_test(request ): 
    data = {
       ' name ' : ' dsb ' , ' age ' : ' 25 ' }
    
      




      return HttpResponse(json.dumps(data),Content-Type='application/json')

 

posted @ 2018-12-04 15:01 You are not as important as you think Read ( ... ) Comment ( ... ) Edit Favorites

Guess you like

Origin blog.csdn.net/bruce_van/article/details/89443051
063
063