如何在Python中对装饰器进行分组 [英] How to group decorators in Python

查看:64
本文介绍了如何在Python中对装饰器进行分组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Flask中,我为每条路线使用了一组装饰器,但是代码丑陋:

In Flask I'm using a set of decorators for each route, but the code is "ugly":

@app.route("/first")
@auth.login_required
@crossdomain(origin='*')
@nocache
def first_page:
    ....

@app.route("/second")
@auth.login_required
@crossdomain(origin='*')
@nocache
def second_page:
    ....

我希望有一个将所有分组的声明其中有一个装饰器:

I would prefer to have a declaration that groups all of them with a single decorator:

@nice_decorator("/first")
def first_page:
    ....

@nice_decorator("/second")
def second_page:
    ....

我试图按照我可以在Python中将两个装饰器组合成一个装饰器吗?但我无法使其工作:

I tried to follow the answer at Can I combine two decorators into a single one in Python? but I cannot make it working:

def composed(*decs):
    def deco(f):
        for dec in reversed(decs):
            f = dec(f)
        return f
    return deco

def nice_decorator(route):
    composed(app.route(route),
             auth.login_required,
             crossdomain(origin="*"),
             nocache)

@nice_decorator("/first")
def first_page:
    ....

因为我没有此错误无法理解:

because of this error that I don't understand:

@nice_decorator("/first")
TypeError: 'NoneType' object is not callable

在其中一个注释之后,我用另一种可行的形式对其进行了定义,但无法指定route参数:

Following one of the comments I defined it with another form that works but without the possibility to specify the route parameter:

new_decorator2 = composed(app.route("/first"),
                          auth.login_required,
                          crossdomain(origin="*"),
                          nocache)

是否可以定义一个

推荐答案

您没有正确定义组成。您需要将 nice_decorator 的定义更改为以下内容:

You're not defining the composition correctly. You need to change the definition of nice_decorator to something like this:

def nice_decorator(route):
    return composed(
        app.route(route),
        auth.login_required,
        crossdomain(origin="*"),
        nocache
    )

您的先前版本实际上未返回任何内容。 Python不像Ruby或Lisp,后者的最后一个表达式是返回值。

Your previous version never actually returned anything. Python isn't like Ruby or Lisp where the last expression is the return value.

这篇关于如何在Python中对装饰器进行分组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆