1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
|
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)
|