我想寫一些代碼來區域傳輸DNS區域,然後解析記錄並將它們放入數據庫中。我從來沒有在python中使用過類,我認爲這可能和學習如何使用它們一樣好。不知道我在這裏做錯了什麼。這是在Python版本2.6上運行的。我可以得到一些指導嗎?在理解如何使用類時遇到困難。如何爲這些DNS數據庫方法創建一個Python類?
代碼:
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)[[email protected] ]$ 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 _is_,現在您需要創建一個sqlfoo(「實例」),然後執行sqlfoo事物(「方法」)。這是面向對象編程的核心概念。谷歌,我會寫一個簡短的例子(如果有人不打我) – mhopeng