grocy-cli/grocy/request.py

39 lines
1.1 KiB
Python
Raw Normal View History

2019-06-16 23:54:10 -05:00
from grocy.conf import Configuration
from requests import session
2019-06-16 23:54:10 -05:00
import logging
import cachecontrol
sess = cachecontrol.CacheControl(session())
2019-06-16 23:54:10 -05:00
class Request(object):
def __init__(self, method, url, resource=None):
2019-06-16 23:54:10 -05:00
self.conf = Configuration()
self.conf.load()
self.url = url
self.resource = resource
2019-06-16 23:54:10 -05:00
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)
else:
r = sess.request(method=self.method, url=self.url, headers=self.headers)
2019-06-16 23:54:10 -05:00
if r.raise_for_status():
logger.error(r.raise_for_status())
logger.error(r.text)
2019-06-16 23:54:10 -05:00
raise r.raise_for_status()
if r.status_code != 204:
return r.json()