grocy-cli/grocy/request.py

40 lines
1.1 KiB
Python

from grocy.conf import Configuration
from requests import session
import logging
import cachecontrol
sess = cachecontrol.CacheControl(session())
class Request(object):
def __init__(self, method, url, resource=None):
self.conf = Configuration()
self.conf.load()
self.url = url
self.resource = resource
self.method = method
self.headers = {
'Content-Type': 'application/json',
'Accept': 'application/json'
}
if self.conf.token:
self.headers[self.conf.API_KEY_HEADER] = self.conf.token
def send(self):
logger = logging.getLogger('request.send')
if self.resource:
r = sess.request(method=self.method, url=self.url, headers=self.headers, json=self.resource)
print(r.text)
else:
r = sess.request(method=self.method, url=self.url, headers=self.headers)
if r.raise_for_status():
logger.error(r.raise_for_status())
logger.error(r.text)
raise r.raise_for_status()
if r.status_code != 204:
return r.json()