【问题标题】:How do I create a Python class for these DNS database methods?如何为这些 DNS 数据库方法创建 Python 类?
【发布时间】:2016-02-12 18:40:31
【问题描述】:

我正在尝试编写一些代码来区域传输 DNS 区域,然后解析记录并将它们放入数据库中。我以前从未在 python 中使用过类,我认为这可能是学习如何使用它们的好时机。不知道我在这里做错了什么。这是在 Python 2.6 版上运行的。我可以得到一些指导吗?很难理解如何使用类。

代码:

import pymysql
import time
import dns.zone
import dns.query
from pprint import pprint
from dns.exception import DNSException
from dns.rdataclass import *
from dns.rdatatype import *


a_records = {}
cname_records = {}

... # excluding db connection credentials

cur = conn.cursor()

try:
    zone = dns.zone.from_xfr(dns.query.xfr(ns, domain))
    print "zone xferred"
except DNSException, e:
    print e.__class__, e


def main():   
    compile_records()

    for key, value in a_records.iteritems():
        sqlfoo.select_a(domain, key, value)
    for key, value in cname_records.iteritems():
        sqlfoo.select_cname(domain, key, value)

def compile_records(): 
    for (name, ttl, rdata) in zone.iterate_rdatas('A'):
        a_records[name.to_text()] = rdata.to_text()
    for (name, ttl, rdata) in zone.iterate_rdatas('CNAME'):
        cname_records[name.to_text()] = rdata.to_text()


class sqlfoo:

    def __init__(self, domain, subdomain, ip, cname):
        self.domain = domain
        self.subdomain = subdomain
        self.ip = ip
        self.cname = cname
        self.results = results

    def select_a(self, domain, subdomain, ip):
        build_select = """
                        SELECT domain, subdomain, cname, ip 
                        FROM zones 
                        WHERE domain = %s 
                        AND subdomain = %s 
                        AND ip = %s;
                       """
        select_params = [ domain, subdomain, ip ]
        cur.execute(build_select, select_params)
        results = cur.fetchall()
        if not any(results): # if the row isn't found, add it
            print domain, subdomain, ip
            self.insert_a(domain, subdomain, ip)


    def select_cname(self, domain, subdomain, cname):
        build_select = """
                        SELECT domain, subdomain, cname, ip 
                        FROM zones 
                        WHERE domain = %s 
                        AND subdomain = %s 
                        AND cname = %s;
                       """
        select_params = [ domain, subdomain, cname ]
        cur.execute(build_select, select_params)
        results = cur.fetchall()
        if not any(results): # if the row isn't found, add it
            print domain, subdomain, cname
            self.insert_cname(domain, subdomain, cname)

    def insert_a(domain, subdomain, ip):
        build_insert = """
                        INSERT INTO zones
                        (Id,
                         domain,
                         record_type,
                         subdomain,
                         cname,
                         first_seen)
                        VALUES
                        (NULL, %s, `A`, %s, %s, %s);
                       """

        insert_params = [ domain, subdomain, ip, current_epoch ]
        cur.execute(build_insert, insert_params)

    def insert_cname(domain, subdomain, ip):
        build_insert = """
                        INSERT INTO zones
                        (Id,
                         domain,
                         record_type,
                         subdomain,
                         cname,
                         first_seen)
                        VALUES
                        (NULL, %s, `CNAME`, %s, %s, %s);
                       """

        insert_params = [ domain, subdomain, cname, current_epoch ]
        cur.execute(build_insert, insert_params)


main()

cur.close()
conn.close()

当我运行代码时,我得到以下输出。

    (venv)[user@server ]$ python zone-etl.py 
    zone xferred
    Traceback (most recent call last):
      File "zone-etl.py", line 125, in <module>
        main()
      File "zone-etl.py", line 42, in main
        sqlfoo.select_a(domain, key, value)
    TypeError: unbound method select_a() must 
be called with sqlfoo instance as first argument (got str instance instead)

【问题讨论】:

  • 您已经定义了 sqlfoo 是什么,现在您需要创建一个 sqlfoo(一个“实例”),然后它会执行 sqlfoo 的事情(“方法”)。这是面向对象编程的核心概念。谷歌一下,我会写一个简短的例子(如果有人没有打败我)

标签: python database class oop dns


【解决方案1】:

您需要创建类的实例才能使用这些方法。 这是一个例子:

class Employee:
    def __init__(self, name, salary):
        self.name = name
        self.salary = salary

    def displayEmployee(self):
       print "Name : ", self.name,  ", Salary: ", self.salary

emp = Employee("Aaron", 5000)
emp.displayEmployee()

【讨论】:

    【解决方案2】:

    你必须在使用它之前实例化你的类。

    当您致电sqlfoo 时,您实际上应该执行以下操作:

    sqlfoo_instance = sqlfoo(domain_value, subdomain_value, ip_value, cname_value)
    
    ...
    for key, value in a_records.iteritems():
        sqlfoo.select_a(domain, key, value)
    for key, value in cname_records.iteritems():
        sqlfoo.select_cname(domain, key, value)
    ...
    

    在您的情况下,我建议您首先对面向对象编程更加熟悉,因为您在那里所做的只是创建更多样板代码来执行与使用过程编程相同的事情。因此,您将获得 OOP 的好处。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-03-29
      • 2010-10-26
      • 1970-01-01
      • 2021-04-07
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多