装饰器在Python-Flask中

时间:2017-02-09 10:27:26

标签: python flask

#==========================================
# Current API
#==========================================

@blueprint.route('/list/<int:type_id>/', methods=["GET"])
@blueprint.route('/list/<int:type_id>/<int:object_id>', methods=["GET"])
@blueprint.route('/list/<int:type_id>/<int:object_id>/<int:cost_id>', methods=["GET"])
@login_required
def get_list(type_id, object_id=None, cost_id=None):
    # Do something 
    pass

我们在Flask项目中使用蓝图进行API分组。

现在要求编写一个装饰器,用于验证在URL中传递的API参数,如type_id,object_id,cost_id等

#==========================================
# New Requested feature in API
#==========================================
from functools import wraps

def request_validator():
"""
This function will validates requests and it's parameters if necessary
"""

    def wrap(f):
        @wraps(f)
        def wrapped(self, *args, **kwargs):

            # TODO -- Here I want to validate before actual handler
            # 1) type_id, 
            # 2) object_id, 
            # 3) cost_id
            # And allow handler to process only if validation passes Here

            if type_id not in [ 1,2,3,4,5 ]:
                return internal_server_error(errormsg="Invalid Type ID")

        return f(self, *args, **kwargs)
    return wrapped
return wrap


@blueprint.route('/list/<int:type_id>/', methods=["GET"])
@blueprint.route('/list/<int:type_id>/<int:object_id>', methods=["GET"])
@blueprint.route('/list/<int:type_id>/<int:object_id>/<int:cost_id>', methods=["GET"])
@login_required
@request_validator
def get_list(type_id, object_id=None, cost_id=None):
    # Do something 
    pass

但是我得到了beow错误并且无法运行应用程序,我错过了什么?

TypeError: request_validator() takes 0 positional arguments but 1 was given

1 个答案:

答案 0 :(得分:1)

你的request_validator装饰者应该接受函数作为参数。当你写:

@request_validator
def get_list():
    pass

它的含义与:

相同
def get_list():
    pass
get_list = request_validator(get_list)

所以你的装饰师应该看起来像这样(比你的例子简单一点):

def request_validator(f):
    @wraps(f)
    def wrapped(*args, **kwargs):
        if type_id not in [ 1,2,3,4,5 ]:
            return internal_server_error(errormsg="Invalid Type ID")
        return f(*args, **kwargs)
    return wrapped