如何比较装饰器中的更多参数?

时间:2018-03-26 17:35:44

标签: python decorator

我必须编写简单的JSON验证器@mydecorator。装饰器必须检查提交的json是否仅包含装饰器参数中列出的元素。对于其他内容,它应该引发ValueError

我试着这样做:

sent_json = {"first_name": "James", "last_name": "Bond"}

def mydecorator(first_arg, second_arg, *args, **kwargs):
    def decoratored(f):
        if first_arg and second_arg in ' {0} '.format(f()):
            return len(sent_json)
        else:
            return ValueError('could not find')
    return decoratored

@mydecorator('first_name', 'last_name')
def hello():
    return sent_json

print(hello)

但是我不知道如何提交和比较装饰器中的更多参数,例如,当用户在装饰器中使用两个以上的参数时......例如。三,四或更多。

例如

@validate_json('first_name', 'last_name')
def process_json(json_data):
    return len(json_data)

result = process_json('{"first_name": "James", "last_name": "Bond"}')
assert result == 44

process_json('{"first_name": "James", "age": 45}')
> ValueError


process_json('{"first_name": "James", "last_name": "Bond", "age": 45}')
> ValueError

1 个答案:

答案 0 :(得分:1)

如果我理解正确的话。

sent_json = {"first_name": "James", "last_name": "Bond"}


def mydecorator(*json_arguments, **kwargs):
    def decorated(f):
        result = f()

        for json_argument in json_arguments:
            if json_argument not in result:
                raise ValueError("Could not find {}".format(json_argument))
        return len(result)
    return decorated


@mydecorator('first_name', 'last_name')
def hello():
    return sent_json

print(hello)

注意:如果你还想装饰带参数的函数,这将会中断。

以下内容也将正确处理该案例(但与原始符号略有不同):

sent_json = {"first_name": "James", "last_name": "Bond"}


def mydecorator(json_arguments, *args, **kwargs):
    def decorated(f):
        result = f(*args, **kwargs)

        for json_argument in json_arguments:
            if json_argument not in result:
                raise ValueError("Could not find {}".format(json_argument))
        return len(result)
    return decorated


@mydecorator(json_arguments=('first_name', 'last_name',))
def hello():
    return sent_json

print(hello)