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