1

I have to write the simply JSON validator @mydecorator. The decorator has to to check whether the submitted json contains only the elements listed in the decorator's arguments. For other content, it should raise a ValueError.

I try to do in this way:

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)

But I don't know how to submit and compare more arguments in the decorator for example, when user uses more than two arguments in decorator...e.g. three, four, or more.

for example

@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 Answers1

1

If i understand correctly..

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)

Note: This will break if you also want to decorate functions that take arguments.

The following will also handle that case properly (but deviates somewhat from your original notation):

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)
Nablezen
  • 362
  • 2
  • 10