The decorator inside the class does not receive values

I have a decorator that checks the json response that I get with requests. I also wrapped some query logic in a class that accepts a schema that the decorator needs to validate. I tried using the decorator in the get function of the class, but every time I try to do this, I get an error like:

TypeError: get() takes exactly 1 argument (0 given)

I know that if you use a decorator in a class method, you need to set self = None in the decorator.

Here is the code:

schema = {'pid': int,
          'description': str}

def validator(schema):
    def _validator(f):
        @wraps(f)
        def wrapped(self=None):
            print f
            check = all([isinstance(v, schema[k]) for k,v in f().iteritems() if v])
            return f() if check else None
        return wrapped
    return _validator


class Data(object):
    ''' Base request wrapper to use for all apis
    accepts a validator schema to check the type of response values. '''

    def __init__(self, base_url, schema=None, debug=False):
        self.base_url = base_url
        self.schema = schema

    def __getattr__(self,key):
        new_base = self.append_to_url(self.base_url, key)
        return self.__class__(base_url=new_base)

    def __getitem__(self,key):
        return self.__getattr__(key)

    # def __call__(self, **kwargs):
    #     self.base_url = self.base_url[:-1]
    #     return self.get(self.base_url, **kwargs)

    def append_to_url(self, base_url, param):
        return '{}{}/'.format(base_url, param)

    @validator(schema)
    def get(self, **kwargs):
        try:
            r = requests.get(self.base_url[:-1], **kwargs)
            r.raise_for_status()
            return r.json()

        except requests.exceptions.ConnectionError as e:
            raise errors.ApiError(e)

        except requests.exceptions.HTTPError as e:
            raise errors.ApiError(e)

product_details = Data('my_api_url', schema).shoes['10'].get()

I think this is because in my validator I initialize f (), which is a get function that expects itself. I tried passing myself to f () in the decorator, but this also gives the same error. I even tried to initialize the get function using the __call__ method, but this gives a get function that expects 1 arg argument and 2.

. , , , , - , .

+4
1

wrapped, , get. , get, f(), .. - .

, self :

import functools

def validator(schema):
    def _validator(f):
        @functools.wraps(f)
        def wrapper(self):
            # pass self to the wrapped function
            result = f(self)
            return 'wrapped {} {}'.format(schema, result)
        return wrapper
    return _validator

class Data(object):
    @validator('test')
    def get(self):
        return 'data'

print(Data().get())
# wrapped test data

self , *args **kwargs , . :

import functools

def validator(schema):
    def _validator(f):
        @functools.wraps(f)
        def wrapped(*args, **kwargs):
            # pass aribitrary args to the wrapped function
            # for greater flexibility
            result = f(*args, **kwargs)
            return 'wrapped {} {}'.format(schema, result)
        return wrapped
    return _validator

class Data(object):
    @validator('test')
    def get(self):
        return 'data'

@validator('test2')
def get():
    return 'data2'

print(Data().get())
# wrapped test data
print(get())
# wrapped test2 data2
+1

All Articles