Article From:https://www.cnblogs.com/fawaikuangtu123/p/9970147.html

1. Ornaments generally talk about this code, but this blog will introduce more:

def deco(func):
    def wrapper():
        print("start")
        func() #Calling functionPrint ("end")Return wrapper@decoDef myfun ():Print "run"Myfun ()

2. Decorative function of arbitrary parameters:

def deco(func):
    def warpper(*args,**kwargs):
        print("start")
        func(*args,**kwargs)
        print("end")
    return warpper
     
@deco
def myfun1(param1):
    print "run with param %s"%(param1)

Decorator rewrites function name and annotation document, @wraps (func) can solve this problem.

from functools import wraps

def deco(func):
    @wraps(func)
    def warpper(*args,**kwargs):
        print("start")
        func(*args,**kwargs)
        print("end")
    return warpper

3.django Custom Decorator to Realize Login Verification

def Check_Login(func):  #Custom login validation decoratorDef warpper (request, * args, ** kwargs):Is_login = request. session. get ('IS_LOG)IN', False)If is_login:Func (request, * args, ** kwargs)Else:Return HttpResponseRedirect ("/polls/login_user")Return warpperDef login_user (request):If request. method =='POST':Form = LoginForm (request. POST)If form.is_valiD ():# Get post data, such as {'username': u'yang1','password': 111}All_data = form. clean()U = all_data ['Form_username']P = all_data ['Form_password']Exist = User.Objects. filter (username = u, password = p). first ()If exist:Request.seSsion ['IS_LOGIN'] = True # Sets the random field value of sessionRequest. session ['uname'] = exist. usernamE # Set the uname field as the logged-in userReturn HttpResponseRedirect ('/polls/home')Else:Return HttpResponse ("Account or password error")Else:Form = LoginForm ()Return reNder (request,'polls/login_user.html', {form': form})@Check_LoginDef home (request):Username = request. session. get ('uname', False) # Gets the login usernameReturn render (request,'polls/ho)Me. html', {username': username}

4. Decorators with parameters

At this time need to add a layer of function, in fact, the definition of a decorator factory function.

Call it and match the required parameters to return the appropriate decorator.

from functools import wraps
 
def logit(logfile='out.log'):
    def logging_decorator(func):
        @wraps(func)
        def wrapped_function(*args, **kwargs):
            log_string = func.__name__ + " was called"
            print(log_string)
            # Open logfile and write contentWith open (logfile,'a') as open_file:# Now type the log to the specified loGfileOpen_file. write (log_string +' n')Return func (* args,** kwargs))Return wrapped_functionReturn logging_decorator@logit ()Def myfunc1 ():PAss

5. Decoration

And sometimes you want to send an email to the question that attracts your attention, but also keep a log, keep a record.

from functools import wraps
 
class logit(object):
    def __init__(self, logfile='out.log'):
        self.logfile = logfile
 
    def __call__(self, func):
        @wraps(func)
        def wrapped_function(*args, **kwargs):
            log_string = func.__name__ + " was called"
            print(log_string)
            # Open logfile and writeWith open (self. log file,'a') as opened_file:# Now type the log to the specifiedfileOpen_file. write (log_string +' n')# Now, send a notificationSelf.Notify ()Return func (* args, ** kwargs)Return wrapped_functionDef notiFY (self):# logit logs, nothing elsePass

The use of class decorators mainly depends on the u call_ method of the class, when the @ form is used to attach the decorator to the function,

will call this method. This implementation has an additional advantage that it is cleaner than nested functions.

Create subclasses for logit to add email functions:

class email_logit(logit):
    '''
    An implementation version of Logit that can send an email to the administrator when a function is called''Def_u init_ (self, email='admin@myproject.com',* args(**kwargs):Self.email = emailSuper (email_logit, self). u init_(* args, ** kwargs)Def notify (self):Send an email to self.email65507Pass

From now on, @email_logit will have the same effect as @logit.

But on the basis of logging, an additional email will be sent to the administrator.

There is another & lt; & gt;, a little deep, do not understand, when used to study.

Reference Address:http://www.runoob.com/w3cnote/python-func-decorators.html

Reference Address:https://www.cnblogs.com/honey-badger/p/8978168.html

Leave a Reply

Your email address will not be published. Required fields are marked *