Home > Backend Development > Python Tutorial > Python合并多个装饰器小技巧

Python合并多个装饰器小技巧

WBOY
Release: 2016-06-10 15:14:13
Original
1226 people have browsed it

django程序,需要写很多api,每个函数都需要几个装饰器,例如

复制代码 代码如下:

@csrf_exempt 
@require_POST 
def  foo(request): 
    pass 

既然那么多个方法都需要写2个装饰器,或者多个,有啥办法把多个合并成一行呢?
上面的函数执行过程应该是
复制代码 代码如下:

csrf_exempt(require_POST(foo)) 

修改成
复制代码 代码如下:

def compose(*funs): 
    def deco(f): 
        for fun in reversed(funs): 
            f = fun(f) 
        return f 
    return deco
 
函数改写成
复制代码 代码如下:

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

参考:
Can I combine two decorators into a single one in Python

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