ansible-role-elasticsearch/module_utils/elasticsearch_api.py

49 lines
1.3 KiB
Python

#!/usr/bin/python
import requests
import base64
class ElasticsearchApi:
def __init__(self, url, user, password):
self.url = url
self.basic = None
if user and password:
self.basic = requests.auth.HTTPBasicAuth(user, password)
def get(self, path):
r = requests.get(
'{}/{}'.format(self.url, path),
auth=self.basic
)
if r.status_code == 500:
raise Exception('Server return 500 error: {}'.format(r.text))
return r.status_code, r.json()
def post(self, path, data):
r = requests.post(
'{}/{}'.format(self.url, path),
auth=self.basic,
json=data
)
if r.status_code == 500:
raise Exception('Server return 500 error: {}'.format(r.text))
elif r.status_code == 401:
raise Exception('Authentification has failed')
elif r.status_code != 200:
raise Exception('Server return an unknown error: {}'.format(r.text))
def put(self, path, data):
r = requests.put(
'{}/{}'.format(self.url, path),
auth=self.basic,
json=data
)
if r.status_code == 500:
raise Exception('Server return 500 error: {}'.format(r.text))
elif r.status_code == 401:
raise Exception('Authentification has failed')
elif r.status_code != 200:
raise Exception('Server return an unknown error: {}'.format(r.text))