简体   繁体   English

Python Flask中的装饰器

[英]Decorator in 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

We are using blueprints for API grouping in our Flask project. 我们在Flask项目中将蓝图用于API分组。

Now requirement here is to write a decorator which validates the API parameter passed in URL, like type_id, object_id,cost_id etc 现在的要求是编写一个装饰器,以验证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

But I am getting beow error and not able to run the application, Am I missing anything? 但是我遇到了beow错误,无法运行该应用程序,我丢失了什么吗?

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

Your request_validator decorator should accept function as argument. 您的request_validator装饰器应接受函数作为参数。 When you write: 当你写:

@request_validator
def get_list():
    pass

it means the same as: 它的含义与:

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

So your decorator should look like this (a bit simpler than in your example): 因此,您的装饰器应如下所示(比您的示例简单一些):

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM