ratatouille/src/generic/http_api.py

43 lines
1.4 KiB
Python

import logging
import requests
import time
class Http_api():
def __init__(self,name,url,token=None):
self.name = name
self.url = url
self.token = token
api_status = self.build_request('api/')
if api_status.status_code != 200:
logging.warning(name+' not available')
def build_request(self,endpoint,method = 'get', content = {},retry=0):
url = self.url+endpoint
if self.token:
headers = {
"content-type": "application/json; charset=ISO-8859-1",
"Authorization": "Bearer "+self.token,
}
else:
headers = {
"content-type": "application/json",
}
try:
if method == 'get':
response = requests.get(url, headers=headers)
return response
if method == 'post':
response = requests.post(url, headers=headers, json=content)
return response
except Exception as e:
if retry < 5:
logging.warning(e)
logging.warning('retry http request on '+self.url+' '+endpoint+' '+str(retry)+' / 5')
time.sleep(5)
self.build_request(endpoint,method,content,retry + 1)
else:
raise TimeoutError('http error on'+self.url+' '+endpoint+' ')