httpnet 0.9.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
httpnet/__init__.py ADDED
File without changes
httpnet/_core.py ADDED
@@ -0,0 +1,520 @@
1
+ import inspect
2
+ import json
3
+ import re
4
+ import sys
5
+ from collections import ChainMap
6
+ from collections.abc import Iterator, Mapping, MutableMapping
7
+ from datetime import datetime
8
+ from enum import Enum
9
+ from types import UnionType
10
+ from typing import Any, ClassVar, Generic, Self, TypeAlias, TypeVar, Union, get_args, get_origin
11
+
12
+ import dateutil.parser
13
+ import requests
14
+
15
+ if sys.version_info >= (3, 14):
16
+ import annotationlib
17
+
18
+ JsonObject: TypeAlias = MutableMapping[str, Any]
19
+
20
+
21
+ class Platform(Enum):
22
+ """
23
+ Known deployments of the API. http.net Internet GmbH also operates the
24
+ same API for hosting.de, only the base URL differs.
25
+ """
26
+
27
+ HTTP_NET = 'https://partner.http.net/api'
28
+ HOSTING_DE = 'https://secure.hosting.de/api'
29
+
30
+ def __repr__(self):
31
+ return f'{self.__class__.__qualname__}.{self.name}'
32
+
33
+ def __str__(self):
34
+ return self.value
35
+
36
+
37
+ class Client:
38
+ USER_AGENT = 'HTTP.NET Partner API Python client 1.0'
39
+ BASE_URL = str(Platform.HTTP_NET)
40
+ VERSION = 'v1'
41
+ FORMAT = 'json'
42
+ DEFAULT_TIMEOUT = 180
43
+
44
+ def __init__(self, auth_token: str, owner_account_id: str | None = None,
45
+ timeout: float | tuple[float, float] | None = None,
46
+ base_url: Platform | str = Platform.HTTP_NET) -> None:
47
+ self.auth_token = auth_token
48
+ self.base_url = str(base_url).rstrip('/')
49
+ self.owner_account_id = owner_account_id
50
+ self.timeout: float | tuple[float, float] = Client.DEFAULT_TIMEOUT
51
+ if isinstance(timeout, tuple):
52
+ if all(t > 0 for t in timeout):
53
+ self.timeout = timeout
54
+ elif timeout is not None and timeout > 0:
55
+ self.timeout = timeout
56
+ self.__session = requests.Session()
57
+ self.__session.headers.update({'User-Agent': Client.USER_AGENT})
58
+
59
+ def call(self, service: str, method: str,
60
+ parameters: Mapping[str, Any] | None = None) -> JsonObject:
61
+ """
62
+ Calls the method of a service.
63
+
64
+ :param service: Name of the service
65
+ :param method: Name of the method
66
+ :param parameters: Mapping of input parameters
67
+ :return: JSON data structure of the response
68
+ """
69
+ url = f'{self.base_url}/{service}/{Client.VERSION}/{Client.FORMAT}/{method}'
70
+ request: ChainMap[str, Any] = ChainMap({
71
+ 'authToken': self.auth_token,
72
+ })
73
+ if self.owner_account_id:
74
+ request['ownerAccountId'] = self.owner_account_id
75
+ if parameters is not None:
76
+ request.maps.append(dict(parameters))
77
+ response = self.__session.post(url, data=json.dumps(dict(request)), timeout=self.timeout)
78
+ response.raise_for_status()
79
+ return response.json()
80
+
81
+
82
+ def camel_case(snake_str: str) -> str:
83
+ first, *others = snake_str.split('_')
84
+ return ''.join([first.lower(), *map(str.title, others)])
85
+
86
+
87
+ def snake_case(camel_str: str) -> str:
88
+ s1 = re.sub(r'(.)([A-Z][a-z]+)', r'\1_\2', camel_str)
89
+ return re.sub(r'([a-z0-9])([A-Z])', r'\1_\2', s1).lower()
90
+
91
+
92
+ def _declared_field_names(ns: Mapping[str, Any]) -> list[str]:
93
+ """
94
+ Extracts the names of all annotated fields from a class namespace while the
95
+ class is being created. Since Python 3.14 (:pep:`649`) annotations are
96
+ evaluated lazily and are no longer present in the namespace, so the
97
+ annotation function has to be called instead. The string format is used
98
+ because only the names are of interest and it also copes with annotations
99
+ that reference names which do not exist yet.
100
+ """
101
+ annotations = ns.get('__annotations__')
102
+ if annotations is None and sys.version_info >= (3, 14):
103
+ annotate = ns.get('__annotate_func__')
104
+ if annotate is not None:
105
+ annotations = annotationlib.call_annotate_function(
106
+ annotate, annotationlib.Format.STRING)
107
+ return list(annotations or {})
108
+
109
+
110
+ def _field_types(cls: type) -> Mapping[str, Any]:
111
+ """
112
+ Returns the resolved types of all fields annotated in the body of ``cls``.
113
+ Annotations inherited from base classes are not included.
114
+ """
115
+ return inspect.get_annotations(cls)
116
+
117
+
118
+ class ElementMeta(type):
119
+ def __new__(mcs, typename: str, bases, ns):
120
+ if ns.get('_root', False):
121
+ return super().__new__(mcs, typename, bases, ns)
122
+ fields = _declared_field_names(ns)
123
+ ns['__slots__'] = fields
124
+ # Mirror of ``__slots__`` that is visible to static type checkers.
125
+ ns['_fields'] = tuple(fields)
126
+ return super().__new__(mcs, typename, bases, ns)
127
+
128
+
129
+ def _from_json_value(value, type_):
130
+ if value is None:
131
+ return None
132
+ if type_ is Any:
133
+ return value
134
+ origin = get_origin(type_)
135
+ if origin in (Union, UnionType):
136
+ args = get_args(type_)
137
+ for arg in args:
138
+ if arg is type(None):
139
+ continue
140
+ try:
141
+ return _from_json_value(value, arg)
142
+ except (AttributeError, TypeError, ValueError):
143
+ continue
144
+ # The API uses an empty string to denote an unset value, e.g. for the
145
+ # deletion date of a domain that is not scheduled for deletion.
146
+ if value == '' and type(None) in args:
147
+ return None
148
+ return value
149
+ if origin is not None:
150
+ args = get_args(type_)
151
+ # Mappings have to be handled before the sequence case, iterating one
152
+ # would yield its keys instead of its items.
153
+ if isinstance(origin, type) and issubclass(origin, Mapping):
154
+ value_type = args[1] if len(args) > 1 else None
155
+ return {k: _from_json_value(v, value_type) for k, v in value.items()}
156
+ return [_from_json_value(v, args[0]) for v in value] if args else list(value)
157
+ if type_ is datetime and isinstance(value, str):
158
+ return dateutil.parser.parse(value)
159
+ if isinstance(type_, type) and issubclass(type_, Element):
160
+ return type_.from_json(value)
161
+ if not isinstance(type_, type):
162
+ return value
163
+ return type_(value)
164
+
165
+
166
+ def _to_json_value(value, type_):
167
+ if value is None or isinstance(value, (str, int, float)):
168
+ return value
169
+ if isinstance(value, datetime):
170
+ return value.isoformat()
171
+ if isinstance(value, Element):
172
+ return value.to_json()
173
+ if isinstance(value, (list, tuple)):
174
+ args = get_args(type_)
175
+ item_type = args[0] if args else None
176
+ return [_to_json_value(v, item_type) for v in value]
177
+ if isinstance(value, Mapping):
178
+ args = get_args(type_)
179
+ value_type = args[1] if len(args) > 1 else None
180
+ return {k: _to_json_value(v, value_type) for k, v in value.items()}
181
+ if isinstance(value, Enum):
182
+ return str(value)
183
+ raise TypeError(f'Unknown type: {type_}')
184
+
185
+
186
+ class Element(metaclass=ElementMeta):
187
+ """
188
+ Base class of all objects the API exchanges. Subclasses declare their
189
+ fields as class annotations, from which the conversion to and from JSON is
190
+ derived. Fields that are not passed to the constructor are ``None``.
191
+ """
192
+
193
+ _root = True
194
+ _fields: ClassVar[tuple[str, ...]] = ()
195
+
196
+ def __init__(self, **kwargs) -> None:
197
+ for field in self._fields:
198
+ setattr(self, field, None)
199
+ for field, value in kwargs.items():
200
+ setattr(self, field, value)
201
+
202
+ def __repr__(self) -> str:
203
+ params = ', '.join([f'{field}={getattr(self, field)!r}' for field in self._fields])
204
+ return f'{self.__class__.__qualname__}({params})'
205
+
206
+ def to_json(self) -> JsonObject:
207
+ """
208
+ Converts this element to the JSON data structure of the API. Field
209
+ names are converted from ``snake_case`` to ``camelCase``, fields that
210
+ are ``None`` are omitted.
211
+
212
+ :return: JSON data structure of this element
213
+ """
214
+ fields: JsonObject = {}
215
+ for field, type_ in _field_types(type(self)).items():
216
+ value = getattr(self, field, None)
217
+ if value is not None:
218
+ field_id = camel_case(field)
219
+ fields[field_id] = _to_json_value(value, type_)
220
+ return fields
221
+
222
+ @classmethod
223
+ def from_json(cls, data: JsonObject) -> Self:
224
+ """
225
+ Creates an element from the JSON data structure of the API. Field names
226
+ are converted from ``camelCase`` to ``snake_case``, values are
227
+ converted to the types the fields are annotated with.
228
+
229
+ :param data: JSON data structure as returned by the API
230
+ :return: New element
231
+ :raises KeyError: if the data contains a field this element does not
232
+ declare
233
+ """
234
+ fields: JsonObject = {}
235
+ field_types = _field_types(cls)
236
+ for field_id, value in data.items():
237
+ field = snake_case(field_id)
238
+ try:
239
+ field_type = field_types[field]
240
+ except KeyError as e:
241
+ raise KeyError(f'No field "{field}" defined in API model "{cls.__qualname__}"') from e
242
+ fields[field] = _from_json_value(value, field_type)
243
+ return cls(**fields)
244
+
245
+
246
+ class ServiceException(Exception):
247
+ """
248
+ Raised when the API rejects a request. The message contains every error the
249
+ API reported, each followed by its error code in parentheses.
250
+ """
251
+
252
+
253
+ T = TypeVar('T', bound=Element)
254
+
255
+
256
+ def _element_class_of(service_class: type) -> Any:
257
+ """
258
+ Determines the element class a service class has been parameterized with,
259
+ e.g. ``Contact`` for ``class ContactService(Service[Contact])``.
260
+ """
261
+ for klass in service_class.__mro__:
262
+ # Only the class's own bases matter, inherited ones would yield the type
263
+ # variable of the generic base class instead of a concrete element class.
264
+ for base in klass.__dict__.get('__orig_bases__', ()):
265
+ for arg in get_args(base):
266
+ if isinstance(arg, type) and issubclass(arg, Element):
267
+ return arg
268
+ raise TypeError(f'{service_class.__qualname__} does not specify an element type')
269
+
270
+
271
+ class Service(Generic[T]):
272
+ _MAX_PAGES = 1000000
273
+
274
+ def __init__(self, client: Client) -> None:
275
+ self._client = client
276
+ self._element_class: type[T] = _element_class_of(type(self))
277
+
278
+ @property
279
+ def _service_domain(self) -> str:
280
+ module_name = self.__module__.rsplit('.', 1)[-1]
281
+ return module_name[0].lower() + module_name[1:]
282
+
283
+ @property
284
+ def _element_name(self) -> str:
285
+ class_name = self._element_class.__name__
286
+ return class_name[0].lower() + class_name[1:]
287
+
288
+ @property
289
+ def _id_name(self) -> str:
290
+ return f'{self._element_name}Id'
291
+
292
+ @property
293
+ def _get_method_name(self) -> str:
294
+ return f'{self._element_name}Info'
295
+
296
+ @property
297
+ def _create_method_name(self) -> str:
298
+ return f'{self._element_name}Create'
299
+
300
+ @property
301
+ def _update_method_name(self) -> str:
302
+ return f'{self._element_name}Update'
303
+
304
+ @property
305
+ def _delete_method_name(self) -> str:
306
+ return f'{self._element_name}Delete'
307
+
308
+ @property
309
+ def _find_method_name(self) -> str:
310
+ if self._element_name.endswith('s'):
311
+ return f'{self._element_name}Find'
312
+ else:
313
+ return f'{self._element_name}sFind'
314
+
315
+ @property
316
+ def _find_filter_name(self) -> str:
317
+ """
318
+ Name of the filter field that selects a single element by its ID. The
319
+ API capitalizes these, e.g. ``ContactId`` for the ``contact`` element,
320
+ and rejects unknown ones.
321
+ """
322
+ return f'{self._element_name[0].upper()}{self._element_name[1:]}Id'
323
+
324
+ def _call(self, method: str, parameters: Mapping[str, Any] | None = None) -> JsonObject:
325
+ response = self._client.call(self._service_domain, method, parameters)
326
+ status = str(response.get('status', '')).lower()
327
+ if status not in {'success', 'pending'}:
328
+ errors = response.get('errors') or []
329
+ error_messages = [f'{error["text"]} ({error["code"]}).' for error in errors]
330
+ raise ServiceException(' '.join(error_messages) or f'API returned status "{status}".')
331
+ return response
332
+
333
+ def _get_by_info(self, key: str, /) -> T:
334
+ """
335
+ Retrieves a single element through the ``<element>Info`` method. Only
336
+ few services provide one, see :meth:`get`.
337
+ """
338
+ response = self._call(
339
+ method=self._get_method_name,
340
+ parameters={self._id_name: key}
341
+ )
342
+ response_body = response['response']
343
+ return self._element_class.from_json(response_body)
344
+
345
+ def _get_by_find(self, key: str, /) -> T:
346
+ """
347
+ Retrieves a single element by filtering the listing for its ID, see
348
+ :meth:`get`.
349
+ """
350
+ filters: dict[str, Any] = {self._find_filter_name: key}
351
+ try:
352
+ return next(self.find(limit=1, page=1, **filters))
353
+ except StopIteration:
354
+ raise KeyError(key) from None
355
+
356
+ def get(self, key: str, /) -> T:
357
+ """
358
+ Retrieves a single element by its ID.
359
+
360
+ Most services have no ``<element>Info`` method, so the element is
361
+ looked up by filtering the listing for its ID. Services that do provide
362
+ one, such as :class:`~httpnet.domain.DomainService`, override this.
363
+
364
+ :param key: ID of the element
365
+ :return: The element
366
+ :raises KeyError: if no element with this ID exists
367
+ """
368
+ return self._get_by_find(key)
369
+
370
+ def _find_parameters(self, limit: int | None = None, sort: str | None = None,
371
+ filters: Mapping[str, Any] | None = None) -> JsonObject:
372
+ parameters: JsonObject = {}
373
+ if limit:
374
+ parameters['limit'] = limit
375
+ if sort:
376
+ if sort.startswith('~'):
377
+ sort_params = dict(field=sort.lstrip('~'), order='desc')
378
+ else:
379
+ sort_params = dict(field=sort, order='asc')
380
+ parameters['sort'] = sort_params
381
+ if filters:
382
+ parameters['filter'] = dict(
383
+ subFilterConnective='AND',
384
+ subFilter=[
385
+ dict(field=field, value=json.dumps(value).strip('"').replace(r'\"', '"'))
386
+ for field, value in filters.items()
387
+ ]
388
+ )
389
+ return parameters
390
+
391
+ def find(self, limit: int | None = None, page: int | None = None,
392
+ sort: str | None = None, **filters) -> Iterator[T]:
393
+ """
394
+ Retrieves all elements matching the given filters. The results are
395
+ fetched page by page while the returned iterator is consumed.
396
+
397
+ :param limit: Number of elements per request, the API defaults to 25
398
+ :param page: Number of the only page to retrieve. By default all pages
399
+ are retrieved.
400
+ :param sort: Name of the field to sort by, prefixed with ``~`` for
401
+ descending order
402
+ :param filters: Field names and values to filter by, as named by the
403
+ API. An asterisk in a value matches any number of characters.
404
+ :return: Iterator over the matching elements
405
+ """
406
+ parameters = self._find_parameters(limit=limit, sort=sort, filters=filters)
407
+ if page:
408
+ page_range = range(page, page + 1)
409
+ else:
410
+ page_range = range(1, Service._MAX_PAGES)
411
+ for page in page_range:
412
+ parameters['page'] = page
413
+ response = self._call(
414
+ method=self._find_method_name,
415
+ parameters=parameters
416
+ )
417
+ response_body = response.get('response', {})
418
+ for json_element in (response_body.get('data') or []):
419
+ element = self._element_class.from_json(json_element)
420
+ yield element
421
+ total_pages = response_body.get('totalPages', 0)
422
+ if total_pages == 0 or page == total_pages:
423
+ break
424
+
425
+ def count(self, sort: str | None = None, **filters) -> int:
426
+ """
427
+ Returns the number of elements matching the given filters without
428
+ retrieving them. This is a single request, the API reports the total
429
+ number of matches for every listing.
430
+
431
+ :param sort: Name of the field to sort by, ignored for the result
432
+ :param filters: Field names and values to filter by
433
+ :return: Number of matching elements
434
+ """
435
+ response = self._call(
436
+ method=self._find_method_name,
437
+ parameters={**self._find_parameters(limit=1, sort=sort, filters=filters), 'page': 1}
438
+ )
439
+ return response.get('response', {}).get('totalEntries', 0)
440
+
441
+ def __len__(self) -> int:
442
+ """
443
+ Returns the total number of elements of this service.
444
+
445
+ Note that this makes the service a sized iterable, so ``list(service)``
446
+ asks the API for the number of elements before it starts iterating.
447
+ Use ``list(service.find())`` to avoid that additional request.
448
+ """
449
+ return self.count()
450
+
451
+ def __iter__(self) -> Iterator[T]:
452
+ return self.find()
453
+
454
+
455
+ class CreatableService(Service[T]):
456
+ """
457
+ A service whose ``<element>Create`` method takes a complete element and
458
+ responds with the created one.
459
+ """
460
+
461
+ def create(self, element: T, /) -> T:
462
+ """
463
+ Creates a new element.
464
+
465
+ :param element: Complete element to be created. Its ID is ignored.
466
+ :return: The created element as stored by the API
467
+ """
468
+ response = self._call(
469
+ method=self._create_method_name,
470
+ parameters={self._element_name: element.to_json()}
471
+ )
472
+ return self._element_class.from_json(response.get('response', {}))
473
+
474
+
475
+ class UpdatableService(Service[T]):
476
+ """
477
+ A service whose ``<element>Update`` method takes a complete element and
478
+ responds with the updated one. The element to be updated is identified by
479
+ the ID it carries, all of its other fields are set to the given values.
480
+ """
481
+
482
+ def update(self, element: T, /) -> T:
483
+ """
484
+ Updates an existing element. The element is identified by the ID it
485
+ carries. All of its other fields are set to the given values, fields
486
+ that are not set are reset to their defaults.
487
+
488
+ :param element: Complete element with the new values
489
+ :return: The updated element as stored by the API
490
+ """
491
+ response = self._call(
492
+ method=self._update_method_name,
493
+ parameters={self._element_name: element.to_json()}
494
+ )
495
+ return self._element_class.from_json(response.get('response', {}))
496
+
497
+
498
+ class DeletableService(Service[T]):
499
+ """
500
+ A service whose ``<element>Delete`` method takes the ID of an element.
501
+ """
502
+
503
+ def delete(self, key: str, /) -> None:
504
+ """
505
+ Deletes an element.
506
+
507
+ :param key: ID of the element to be deleted
508
+ """
509
+ self._call(
510
+ method=self._delete_method_name,
511
+ parameters={self._id_name: key}
512
+ )
513
+
514
+
515
+ class CrudService(CreatableService[T], UpdatableService[T], DeletableService[T]):
516
+ """
517
+ A service that follows the generic create/update/delete scheme of the API.
518
+ Services that deviate from it derive from :class:`Service` or from the
519
+ individual base classes and declare their own methods.
520
+ """
httpnet/client.py ADDED
@@ -0,0 +1,38 @@
1
+ from ._core import Client, Platform
2
+ from .dns import NameserverSetService, RecordService, TemplateService, ZoneConfigService, ZoneService
3
+ from .domain import ContactService, DomainService, JobService
4
+ from .email import DomainSettingsService, MailboxService, OrganizationService
5
+
6
+ __all__ = ['HttpNetClient', 'Platform']
7
+
8
+
9
+ class HttpNetClient:
10
+ """
11
+ A client for the http.net Partner API.
12
+
13
+ The same API is operated for hosting.de, pass ``Platform.HOSTING_DE`` as
14
+ ``base_url`` to use it.
15
+ """
16
+
17
+ def __init__(self, auth_token: str, owner_account_id: str | None = None,
18
+ timeout: float | tuple[float, float] | None = None,
19
+ base_url: Platform | str = Platform.HTTP_NET) -> None:
20
+ self.__client = Client(auth_token, owner_account_id=owner_account_id, timeout=timeout,
21
+ base_url=base_url)
22
+
23
+ # Domains
24
+ self.domains = DomainService(self.__client)
25
+ self.domain_contacts = ContactService(self.__client)
26
+ self.domain_jobs = JobService(self.__client)
27
+
28
+ # DNS
29
+ self.dns_zone_configs = ZoneConfigService(self.__client)
30
+ self.dns_records = RecordService(self.__client)
31
+ self.dns_zones = ZoneService(self.__client)
32
+ self.nameserver_sets = NameserverSetService(self.__client)
33
+ self.dns_templates = TemplateService(self.__client)
34
+
35
+ # Email
36
+ self.mailboxes = MailboxService(self.__client)
37
+ self.email_organizations = OrganizationService(self.__client)
38
+ self.email_domain_settings = DomainSettingsService(self.__client)