import json
import requests
import os
from configparser import RawConfigParser, NoSectionError, NoOptionError
class AuthenticationException(Exception):
pass
class RateLimitExceeded(Exception):
pass
class InternalServer(Exception):
pass
class HetznerConfig:
def __init__(self):
config = RawConfigParser()
config.read([os.path.expanduser('~/.hetzner.conf')])
self.api_key = config.get("default", "api_key")
config = HetznerConfig()
def call(endpoint, url_params=None, body=None, method="GET"):
api = "https://api.hetzner.cloud/v1/{}".format(endpoint)
headers = {"Authorization": "Bearer {}".format(config.api_key)}
data = json.dumps(body) if body is not None else None
if method == "GET":
request = requests.get(api, headers=headers, params=url_params)
elif method == "POST" or (method == "GET" and body is not None):
request = requests.post(api, data=data, headers=headers, params=url_params)
elif method == "DELETE":
request = requests.delete(api, headers=headers)
elif method == "PUT":
request = requests.put(api, headers=headers, data=data)
if request.status_code == 401 or request.status_code == 403:
raise AuthenticationException()
if request.status_code == 429:
raise RateLimitExceeded()
if request.status_code == 500:
raise InternalServer(request.text)
if not request.text:
return request.status_code, ""
js = request.json()
return request.status_code, js
def get(*args, **kwargs):
return call(*args, method="GET", **kwargs)
def post(*args, **kwargs):
return call(*args, method="POST", **kwargs)