grocy-cli/grocy/__init__.py

89 lines
2.5 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
2019-05-05 16:06:33 -05:00
def post(self, entity_name, entity):
if type(entity) is not dict:
json_payload = entity.toJSON()
else:
2019-05-05 16:06:33 -05:00
json_payload = entity
url = RestService.COLLECTION_URL_TEMPLATE.format(api_url=self.api_url, entity=entity_name)
2019-05-05 16:06:33 -05:00
r = requests.post(url, json=json.dumps(json_payload), headers=self.headers)
if self.json:
return r.json()
return r.content
def addHeader(self, type, value):
self.headers[type] = value
2019-06-16 23:54:10 -05:00
def addToken(self, value):
2019-06-16 23:54:10 -05:00
self.headers[RestService.API_KEY_HEADER] = value