如何在每个函数调用中使用带有Flask-RESTPlus的装饰器?

时间:2015-10-05 18:56:37

标签: python python-decorators flask-restplus

我有问题将装饰器应用到我的14:17:04,120 INFO [stdout] (http--127.0.0.1-8080-6) 2015-10-05 14:17:04 INFO AutorizadorController:244 - entra 14:17:04,199 INFO [stdout] (http--127.0.0.1-8080-6) 2015-10-05 14:17:04 INFO AutorizadorModelImpl:467 - Entra al turno rechazado 14:17:04,199 INFO [mx.gob.edomex.dgsei.gestion.data.dao.impl.TurnoDAOImpl] (http--127.0.0.1-8080-6) start here 14:17:04,199 INFO [mx.gob.edomex.dgsei.gestion.data.dao.impl.TurnoDAOImpl] (http--127.0.0.1-8080-6) stop here Resource Api参数会应用于每个资源函数,或者我如何理解decorators参数?我的装饰器仅在启动时应用,而不是在每个函数调用时应用。我做错了什么?

decorators

1 个答案:

答案 0 :(得分:6)

There is two decorators levels: API-wide and Resource-wide.

The Api.decorators parameter allow to apply decorators to all resources whereas the Resource.method_decorators will be applied on all method for a given resource.

The problem in your case it that your decorator only call the print once applied and not once called. You should modify your decorator like this:

def my_decorator(func):
    def wrapper(*args, **kwargs):
        print("my decorator")
        return func(*args, **kwargs)
    wrapper.__doc__ = func.__doc__
    wrapper.__name__ = func.__name__
    return wrapper

Notice the __doc__ and __name__ affectations. The first allow to correctly extract the description, the __name__ allow to avoid automatic naming collisions. The name is optional if you manually specify an endpoint for each resource.