cucchiaiata/src/cucchiaiata/common.py

66 lines
2.0 KiB
Python

from os.path import isfile
from requests import get, post
from json import dumps
from typing import Dict
from .config import config
from tiramisu_api import Config
if config.allow_insecure_https:
import warnings
from urllib3.exceptions import InsecureRequestWarning
warnings.simplefilter('ignore', InsecureRequestWarning)
class Common:
def __init__(self):
self.cucchiaiata_config = config
def get_token(self):
if isfile(self.cucchiaiata_config.token_file):
return open(self.cucchiaiata_config.token_file).read()
return ''
def get_error_from_http(self,
req):
try:
json = req.json()
err = json['error']['kwargs']['reason']
except:
err = req.text
return err
def remote_json_to_config(self,
url=None,
config_type=Config):
"retrieves the remote config from the distant api description"
if url is None:
url = self.cucchiaiata_config.remote_url
token = self.get_token()
headers = {'Authorization':'Bearer {}'.format(token)}
req = get(url,
headers=headers,
verify=config.allow_insecure_https)
code = req.status_code
if code != 200:
raise Exception(self.get_error_from_http(req))
json = req.json()
return config_type(json)
def send_data(message: str,
payload: Dict):
final_url = '{}/{}'.format(config.remote_url, message)
ret = post(final_url,
data=dumps(payload),
verify=config.allow_insecure_https)
if ret.status_code != 200:
raise Exception(ret.text)
response = ret.json()
if 'error' in response:
if 'reason' in response['error']['kwargs']:
raise Exception("{}".format(response['error']['kwargs']['reason']))
raise Exception('erreur inconnue')
return response['response']