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 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.
. , , , , - , .