import requests import requests_cache import json requests_cache.install_cache('grocy', allowable_methods=('GET',), expire_after=180) class RestService(object): API_KEY_HEADER = 'GROCY-API-KEY' def __init__(self, api_url, json=False): self.api_url = api_url self.headers = {} self.json = json def get(self, path, id=None): # TODO: change this to a single pattern assume a pattern then stick with it if self.api_url.endswith('/'): url = '{0}{1}'.format(self.api_url, path[1:]) else: url = '{0}{1}'.format(self.api_url, path) if id: url = '{0}/{1}'.format(url, id) r = requests.get(url, headers=self.headers) if r.raise_for_status(): logger.error(r.raise_for_status()) raise r.raise_for_status() if self.json: return r.json() return r.content def delete(self, path, id): api_url = self.api_url if api_url.endswith('/'): url = '{0}{1}'.format(api_url, path[1:]) else: url = '{0}/{1}'.format(api_url, path) r = requests.get(url, headers=self.headers) if r.raise_for_status(): logger.error(r.raise_for_status()) raise r.raise_for_status() if self.json: return r.json() return r.content def post(self, path, payload): api_url = self.api_url if self.api_url.endswith('/'): api_url = api_url[1:] if path.startswith('/'): url ='{0}{1}'.format(api_url, path) else: url = '{0}/{1}'.format(api_url, path) print('{}'.format(url)) r = requests.post(url, data=json.dumps(payload), headers=self.headers) #if r.raise_for_status(): # logger.error(r.raise_for_status()) # raise r.raise_for_status() if self.json: return r.json() return r.content def addHeader(self, type, value): self.headers[type] = value def addToken(self, value): self.headers[RestService.API_KEY_HEADER] = value;