import requests from dataclasses import asdict 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' RESOURCE_URL_TEMPLATE = '{api_url}/objects/{entity}/{objectId}' COLLECTION_URL_TEMPLATE = '{api_url}/objects/{entity}' def __init__(self, api_url, json=False): self.api_url = api_url self.headers = {} self.json = json def put(self, entity_name, entity, entity_id): if type(entity) is not dict: json_payload = entity.toJSON() else: json_payload = entity url = RestService.RESOURCE_URL_TEMPLATE.format(api_url=self.api_url, entity=entity_name, objectId=entity_id) r = requests.put(url, json=json_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 get(self, entity_name, id=None): if not id: url = RestService.COLLECTION_URL_TEMPLATE.format(api_url=self.api_url, entity=entity_name) else: url = RestService.RESOURCE_URL_TEMPLATE.format(api_url=self.api_url, entity=entity_name, objectId=id) r = requests.get(url, headers=self.headers) if 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, entity_name, entity): if type(entity) is not dict: json_payload = entity.toJSON() else: json_payload = entity url = RestService.COLLECTION_URL_TEMPLATE.format(api_url=self.api_url, entity=entity_name) r = requests.post(url, json=json.dumps(json_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;