How to group decorators in Python

In Flask, I use 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 rather have an ad that groups all of them with a single decorator:

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

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

I tried to execute the answer to Can I combine two decorators into one in Python? but I can't get it to work:

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:
    ....

due to this error that I don't understand:

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

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

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

Is it possible to define one decorator with parameters?

+4
source share
1 answer

You are not defining the composition correctly. You need to change the definition nice_decoratorto the following:

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

. Python Ruby Lisp, .

+5

Source: https://habr.com/ru/post/1686874/


All Articles