Home > Backend Development > Python Tutorial > Is it suitable to combine multiple decorators using Python?

Is it suitable to combine multiple decorators using Python?

伊谢尔伦
Release: 2017-06-28 13:24:38
Original
2101 people have browsed it

This article mainly introduces Python Tips for merging multiple decorators. This article uses the method of rewriting and calling function to merge multiple decorators into one line and one function. Call, friends who need it can refer to the

django program. You need to write a lot of APIs. Each function requires several decorators, such as

@csrf_exempt  
@require_POST  
def  foo(request):  
    pass
Copy after login

Since there are so many Each method needs to write two decorators, or more. Is there any way to combine multiple decorators into one line?
The execution process of the above function should be

The code is as follows:

csrf_exempt(require_POST(foo))
Copy after login

is modified to

def compose(*funs):  
    def deco(f):  
        for fun in reversed(funs):  
            f = fun(f)  
        
return f  
return deco
Copy after login

The function is rewritten to

@compose(csrf_exempt, require_POST)  
def foo(request):  
    pass
Copy after login

The above is the detailed content of Is it suitable to combine multiple decorators using Python?. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template