aboutsummaryrefslogtreecommitdiff
path: root/python/hetzner_helper.py
diff options
context:
space:
mode:
Diffstat (limited to 'python/hetzner_helper.py')
-rw-r--r--python/hetzner_helper.py59
1 files changed, 59 insertions, 0 deletions
diff --git a/python/hetzner_helper.py b/python/hetzner_helper.py
new file mode 100644
index 0000000..496e14d
--- /dev/null
+++ b/python/hetzner_helper.py
@@ -0,0 +1,59 @@
1import json
2import requests
3import os
4
5from configparser import RawConfigParser, NoSectionError, NoOptionError
6
7class AuthenticationException(Exception):
8 pass
9
10class RateLimitExceeded(Exception):
11 pass
12
13class InternalServer(Exception):
14 pass
15
16class HetznerConfig:
17 def __init__(self):
18 config = RawConfigParser()
19 config.read([os.path.expanduser('~/.hetzner.conf')])
20
21 self.api_key = config.get("default", "api_key")
22
23config = HetznerConfig()
24
25def call(endpoint, url_params=None, body=None, method="GET"):
26 api = "https://api.hetzner.cloud/v1/{}".format(endpoint)
27 headers = {"Authorization": "Bearer {}".format(config.api_key)}
28 data = json.dumps(body) if body is not None else None
29
30 if method == "GET":
31 request = requests.get(api, headers=headers, params=url_params)
32 elif method == "POST" or (method == "GET" and body is not None):
33 request = requests.post(api, data=data, headers=headers, params=url_params)
34 elif method == "DELETE":
35 request = requests.delete(api, headers=headers)
36 elif method == "PUT":
37 request = requests.put(api, headers=headers, data=data)
38
39 if request.status_code == 401 or request.status_code == 403:
40 raise AuthenticationException()
41
42 if request.status_code == 429:
43 raise RateLimitExceeded()
44
45 if request.status_code == 500:
46 raise InternalServer(request.text)
47
48 if not request.text:
49 return request.status_code, ""
50
51 js = request.json()
52
53 return request.status_code, js
54
55def get(*args, **kwargs):
56 return call(*args, method="GET", **kwargs)
57
58def post(*args, **kwargs):
59 return call(*args, method="POST", **kwargs)