-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathgandi.py
360 lines (291 loc) · 10.8 KB
/
gandi.py
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
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
import logging
import json
import requests
API_URL = "https://api.gandi.net/v5/"
class GandiAPIClient:
"""Wrapper for the Gandi API client.
It handles Gandi API over https for LiveDNS. Logging is done through the
`gandiAPI` logger. See `logging` package documentation for how to configure
it.
"""
def __init__(self, api_key):
"""Initializes the API client.
Args:
api_key: the API key as provided by Gandi.
log_level: logging level (see `logging` package documentation)
"""
self.logger = logging.getLogger("gandiAPI")
self.api_key = api_key
def _request(self, method, url, headers={}, params={}, *args, **kwargs):
self.logger.debug(
"Requesting %s: %s, headers=%r, params=%r, args=%r, kwargs=%r",
method,
url,
headers,
params,
args,
kwargs,
)
headers.update({"Authorization": "Apikey %s" % self.api_key})
response = getattr(requests, method)(
url, headers=headers, params=params, allow_redirects=False, *args, **kwargs
)
self.logger.debug("Got response %r.", response)
response.raise_for_status()
try:
ret = response.json()
except json.decoder.JSONDecodeError as e:
ret = None
self.logger.debug("No valid JSON in the response.")
self.logger.debug("Request {} {} successful.".format(method, response.url))
return ret
def delete(self, *args, **kwargs):
"""Performs a DELETE request.
DELETE request on a given URL that acts like `requests.delete` except
that authentication to the API is automatically done and JSON response
is decoded.
Args:
url: The URL of the requests.
*args: See `requests.delete` parameters.
**kwargs: See `requests.delete` parameters.
Returns:
The JSON-decoded result of the request.
Raises:
requests.exceptions.RequestException: An error occured while
performing the request.
exceptions.PermissionDenied: The user does not have the right
to perform this request.
"""
return self._request("delete", *args, **kwargs)
def get(self, *args, **kwargs):
"""Performs a GET request.
GET request on a given URL that acts like `requests.get` except that
authentication to the API is automatically done and JSON response is
decoded.
Args:
url: The URL of the requests.
*args: See `requests.get` parameters.
**kwargs: See `requests.get` parameters.
Returns:
The JSON-decoded result of the request.
Raises:
requests.exceptions.RequestException: An error occured while
performing the request.
exceptions.PermissionDenied: The user does not have the right
to perform this request.
"""
return self._request("get", *args, **kwargs)
def head(self, *args, **kwargs):
"""Performs a HEAD request.
HEAD request on a given URL that acts like `requests.head` except that
authentication to the API is automatically done and JSON response is
decoded.
Args:
url: The URL of the requests.
*args: See `requests.head` parameters.
**kwargs: See `requests.head` parameters.
Returns:
The JSON-decoded result of the request.
Raises:
requests.exceptions.RequestException: An error occured while
performing the request.
exceptions.PermissionDenied: The user does not have the right
to perform this request.
"""
return self._request("get", *args, **kwargs)
def option(self, *args, **kwargs):
"""Performs a OPTION request.
OPTION request on a given URL that acts like `requests.option` except
that authentication to the API is automatically done and JSON response
is decoded.
Args:
url: The URL of the requests.
*args: See `requests.option` parameters.
**kwargs: See `requests.option` parameters.
Returns:
The JSON-decoded result of the request.
Raises:
requests.exceptions.RequestException: An error occured while
performing the request.
exceptions.PermissionDenied: The user does not have the right
to perform this request.
"""
return self._request("get", *args, **kwargs)
def patch(self, *args, **kwargs):
"""Performs a PATCH request.
PATCH request on a given URL that acts like `requests.patch` except
that authentication to the API is automatically done and JSON response
is decoded.
Args:
url: The URL of the requests.
*args: See `requests.patch` parameters.
**kwargs: See `requests.patch` parameters.
Returns:
The JSON-decoded result of the request.
Raises:
requests.exceptions.RequestException: An error occured while
performing the request.
exceptions.PermissionDenied: The user does not have the right
to perform this request.
"""
return self._request("patch", *args, **kwargs)
def post(self, *args, **kwargs):
"""Performs a POST request.
POST request on a given URL that acts like `requests.post` except that
authentication to the API is automatically done and JSON response is
decoded.
Args:
url: The URL of the requests.
*args: See `requests.post` parameters.
**kwargs: See `requests.post` parameters.
Returns:
The JSON-decoded result of the request.
Raises:
requests.exceptions.RequestException: An error occured while
performing the request.
exceptions.PermissionDenied: The user does not have the right
to perform this request.
"""
return self._request("post", *args, **kwargs)
def put(self, *args, **kwargs):
"""Performs a PUT request.
PUT request on a given URL that acts like `requests.put` except that
authentication to the API is automatically done and JSON response is
decoded.
Args:
url: The URL of the requests.
*args: See `requests.put` parameters.
**kwargs: See `requests.put` parameters.
Returns:
The JSON-decoded result of the request.
Raises:
requests.exceptions.RequestException: An error occured while
performing the request.
exceptions.PermissionDenied: The user does not have the right
to perform this request.
"""
return self._request("put", *args, **kwargs)
class APIElement:
def __init__(self, client, api_endpoint):
self.client = client
self.api_endpoint = api_endpoint
def save(self):
data = self.as_api()
if self.exists:
self.client.put(API_URL + self.api_endpoint, json=data)
else:
self.client.post(API_URL + self.api_endpoint, json=data)
@property
def exists(self):
try:
r = self.client.get(API_URL + self.api_endpoint)
return True
except requests.exceptions.HTTPError:
return False
def fetch(self):
r = self.client.get(API_URL + self.api_endpoint)
self.from_dict(r)
def delete(self):
self.client.delete(API_URL + self.api_endpoint)
class Record(APIElement):
class Types:
A = "A"
AAAA = "AAAA"
ALIAS = "ALIAS"
CAA = "CAA"
CDS = "CDS"
CNAME = "CNAME"
DNAME = "DNAME"
DS = "DS"
KEY = "KEY"
LOC = "LOC"
MX = "MX"
NS = "NS"
OPENPGPKEY = "OPENPGPKEY"
PTR = "PTR"
SPF = "SPF"
SRV = "SRV"
SSHFP = "SSHFP"
TLSA = "TLSA"
TXT = "TXT"
WKS = "WKS"
ENDPOINT = "livedns/domains/{fqdn}/records/{rrset_name}/{rrset_type}"
def __init__(
self,
client,
domain,
rrset_name="",
rrset_type=None,
rrset_values=None,
rrset_ttl=10800,
**kwargs
):
endpoint = self.ENDPOINT.format(
fqdn=domain, rrset_name=rrset_name, rrset_type=rrset_type
)
super().__init__(client, endpoint)
self.rrset_name = rrset_name
self.rrset_type = rrset_type
self.rrset_values = rrset_values
self.rrset_ttl = rrset_ttl
if self.rrset_values is None or self.rrset_type is None:
self.fetch()
@classmethod
def from_name(cls, client, domain, name):
cls(client, domain, rrset_name=name)
def as_dict(self):
return {
"rrset_name": self.rrset_name,
"rrset_type": self.rrset_type,
"rrset_values": self.rrset_values,
"rrset_ttl": self.rrset_ttl,
}
def as_api(self):
return {"rrset_values": self.rrset_values, "rrset_ttl": self.rrset_ttl}
def from_dict(self, d):
self.rrset_name = d["rrset_name"]
self.rrset_type = d["rrset_type"]
self.rrset_values = d["rrset_values"]
self.rrset_ttl = d.get("rrset_ttl", 10800)
def __repr__(self):
return "<Record name=%s, type=%s, values=%r, ttl=%s>" % (
self.rrset_name,
self.rrset_type,
self.rrset_values,
self.rrset_ttl,
)
def __eq__(self, other):
return (
self.rrset_name == other.rrset_name
and self.rrset_type == other.rrset_type
and self.rrset_values == other.rrset_values
and self.rrset_ttl == other.rrset_ttl
)
def __hash__(self):
return hash(repr(self))
class DomainsRecords(APIElement):
ENDPOINT = "livedns/domains/{fqdn}/records"
def __init__(self, client, fqdn, records=None, fetch=True):
endpoint = self.ENDPOINT.format(fqdn=fqdn)
super().__init__(client, endpoint)
self.fqdn = fqdn
self.records = records
if self.records is None and fetch:
self.fetch()
else:
self.records = []
def save(self):
for r in self.records:
r.save()
def from_dict(self, d):
# l is actually an array
if isinstance(d, dict):
l = d["records"]
else:
l = d
logging.getLogger("gandiAPI").debug(l)
self.records = [Record(self.client, self.fqdn, **r) for r in l]
def as_dict(self):
return [r.as_dict() for r in self.records]
def __repr__(self):
return "<DomainsRecords domain=%s, records=%r>" % (self.fqdn, self.records)