grocy-cli/grocy/__init__.py

96 lines
2.7 KiB
Python
Raw Normal View History

import requests
2019-04-28 16:12:05 -05:00
from dataclasses import asdict
2019-03-09 19:02:42 -06:00
import requests_cache
import json
2019-03-09 19:02:42 -06:00
2019-04-28 16:12:05 -05:00
#requests_cache.install_cache('grocy', allowable_methods=('GET',), expire_after=180)
class RestService(object):
API_KEY_HEADER = 'GROCY-API-KEY'
2019-04-28 16:12:05 -05:00
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
2019-04-28 16:12:05 -05:00
def put(self, entity_name, entity, entity_id):
if type(entity) is not dict:
json_payload = entity.toJSON()
else:
2019-04-28 16:12:05 -05:00
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
2019-04-28 16:12:05 -05:00
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, 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)
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;