]> Frank Brehm's Git Trees - pixelpark/admin-tools.git/commitdiff
Adding pp_lib/pdns_record.py
authorFrank Brehm <frank.brehm@pixelpark.com>
Wed, 8 Nov 2017 14:46:24 +0000 (15:46 +0100)
committerFrank Brehm <frank.brehm@pixelpark.com>
Wed, 8 Nov 2017 14:46:24 +0000 (15:46 +0100)
pp_lib/pdns_record.py [new file with mode: 0644]

diff --git a/pp_lib/pdns_record.py b/pp_lib/pdns_record.py
new file mode 100644 (file)
index 0000000..6428cd0
--- /dev/null
@@ -0,0 +1,267 @@
+#!/usr/bin/env python
+# -*- coding: utf-8 -*-
+"""
+@author: Frank Brehm
+@contact: frank.brehm@pixelpark.com
+@copyright: © 2010 - 2017 by Frank Brehm, Publicies Pixelpark GmbH, Berlin
+@summary: An encapsulation class for a DNS record object by PowerDNS API
+"""
+from __future__ import absolute_import
+
+# Standard modules
+import sys
+import os
+import logging
+import copy
+
+# Third party modules
+
+# Own modules
+from .common import pp, to_bytes, to_utf8
+
+from .errors import PpError
+from .obj import PpBaseObjectError, PpBaseObject
+
+__version__ = '0.2.1'
+
+LOG = logging.getLogger(__name__)
+
+# =============================================================================
+class PdnsApiRrsetError(PpBaseObjectError):
+    pass
+
+
+# =============================================================================
+class PdnsApiRecord(PpBaseObject):
+
+    # -------------------------------------------------------------------------
+    def __init__(
+        self, appname=None, verbose=0, version=__version__, base_dir=None, initialized=None,
+        content=None, disabled=False):
+
+        self._content = content
+        self._disabled = False
+        self.disabled = disabled
+
+        super(PdnsApiRecord, self).__init__(
+            appname=appname, verbose=verbose, version=version, base_dir=base_dir)
+
+        if initialized is not None:
+            self.initialized = initialized
+
+    # -----------------------------------------------------------
+    @property
+    def content(self):
+        "The underlying content of this record."
+        return self._content
+
+    # -----------------------------------------------------------
+    @property
+    def disabled(self):
+        "Flag, whether the record is disabled or not."
+        return self._disabled
+
+    @disabled.setter
+    def disabled(self, value):
+        self._disabled = bool(value)
+
+    # -------------------------------------------------------------------------
+    def as_dict(self, short=True):
+        """
+        Transforms the elements of the object into a dict
+
+        @param short: don't include local properties in resulting dict.
+        @type short: bool
+
+        @return: structure as dict
+        @rtype:  dict
+        """
+
+        res = super(PdnsApiRecord, self).as_dict(short=short)
+        res['content'] = self.content
+        res['disabled'] = self.disabled
+
+        return res
+
+    # -------------------------------------------------------------------------
+    def __copy__(self):
+
+        return PdnsApiRecord(
+            appname=self.appname, verbose=self.verbose, base_dir=self.base_dir,
+            initialized=self.initialized, content=self.content, disabled=self.disabled)
+
+    # -------------------------------------------------------------------------
+    def __str__(self):
+        """
+        Typecasting function for translating object structure
+        into a string
+
+        @return: structure as string
+        @rtype:  str
+        """
+
+        return pp(self.as_dict(short=True))
+
+    # -------------------------------------------------------------------------
+    def __repr__(self):
+        """Typecasting into a string for reproduction."""
+
+        out = "<%s(" % (self.__class__.__name__)
+
+        fields = []
+        fields.append("content={!r}".format(self.content))
+        fields.append("disabled={!r}".format(self.disabled))
+        fields.append("appname={!r}".format(self.appname))
+        fields.append("verbose={!r}".format(self.verbose))
+        fields.append("version={!r}".format(self.version))
+
+        out += ", ".join(fields) + ")>"
+        return out
+
+# =============================================================================
+class PdnsApiRrset(PpBaseObject):
+
+    default_ttl = 3600
+
+    # -------------------------------------------------------------------------
+    def __init__(
+        self, appname=None, verbose=0, version=__version__, base_dir=None, initialized=None): 
+
+#        {   'comments': [],
+#            'name': 'www.bmwi.tv.',
+#            'records': [{'content': '77.74.236.5', 'disabled': False}],
+#            'ttl': 3600,
+#            'type': 'A'},
+
+        self.comments = []
+        self._name = None
+        self.ttl = self.default_ttl
+        self._type = None
+        self.records = []
+
+        super(PdnsApiRrset, self).__init__(
+            appname=appname, verbose=verbose, version=version, base_dir=base_dir)
+
+        if initialized is not None:
+            self.initialized = initialized
+
+    # -----------------------------------------------------------
+    @property
+    def name(self):
+        "The name of this record set."
+        return self._name
+
+    # -----------------------------------------------------------
+    @property
+    def type(self):
+        "The type of this record set."
+        return self._type
+
+    # -----------------------------------------------------------
+    @property
+    def ttl(self):
+        "The TTL of this record set."
+        return self._ttl
+
+    @ttl.setter
+    def ttl(self, value):
+        self._ttl = int(value)
+
+    # -----------------------------------------------------------
+    @classmethod
+    def init_from_dict(
+        cls, data, appname=None, verbose=0, version=__version__, base_dir=None, initialized=None):
+
+        if not isinstance(data, dict):
+            raise PdnsApiRecordError("Given data {!r} is not a dict object.".format(data))
+
+        params = {
+            'appname': appname,
+            'verbose': verbose,
+            'version': version,
+            'base_dir': base_dir
+        }
+        if initialized is not None:
+            params['initialized'] = initialized
+
+        rrset = cls(**params)
+
+        if 'comments' in data and data['comments']:
+            for comment in data['comments']:
+                rrset.comments.append(str(comment))
+
+        rrset._name = str(data['name'])
+        rrset._type = str(data['type']).upper()
+        if 'ttl' in data:
+            rrset._ttl = int(data['ttl'])
+
+        if 'records' in data:
+            for single_record in data['records']:
+                record = PdnsApiRecord(
+                    content=single_record['content'], disabled=single_record['disabled'],
+                    **params)
+                record.initialized = True
+                rrset.records.append(record)
+
+        rrset.initialized = True
+
+        return rrset
+
+    # -------------------------------------------------------------------------
+    def as_dict(self, short=True):
+        """
+        Transforms the elements of the object into a dict
+
+        @param short: don't include local properties in resulting dict.
+        @type short: bool
+
+        @return: structure as dict
+        @rtype:  dict
+        """
+
+        res = super(PdnsApiRrset, self).as_dict(short=short)
+        res['name'] = self.name
+        res['type'] = self.type
+        res['ttl'] = self.ttl
+        res['comments'] = copy.copy(self.comments)
+        res['records'] = []
+
+        for record in self.records:
+            res['records'].append(record.as_dict(short))
+
+        return res
+
+    # -------------------------------------------------------------------------
+    def __str__(self):
+        """
+        Typecasting function for translating object structure
+        into a string
+
+        @return: structure as string
+        @rtype:  str
+        """
+
+        return pp(self.as_dict(short=True))
+
+    # -------------------------------------------------------------------------
+    def __copy__(self):
+
+        rrset = PdnsApiRrset(
+            appname=self.appname, verbose=self.verbose, base_dir=self.base_dir,
+            initialized=self.initialized)
+
+        rrset._name = self.name
+        rrset._type = self.type
+        rrset._ttl = self.ttl
+        rrset.comments = copy.copy(self.comments)
+        rrset.records = copy.copy(self.records)
+
+# =============================================================================
+
+if __name__ == "__main__":
+
+    pass
+
+# =============================================================================
+
+# vim: tabstop=4 expandtab shiftwidth=4 softtabstop=4 list