python DNS字典。 __getitem__任何主机,它从系统DNS返回一个随机的ipaddress,表示TTL
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了python DNS字典。 __getitem__任何主机,它从系统DNS返回一个随机的ipaddress,表示TTL相关的知识,希望对你有一定的参考价值。
import random
import time
# if python2, install these batteries first
# ipaddress
import ipaddress
# dnspython
import dns.resolver
NX_EXPIRE = 5 * 60
def dns_query(host):
try:
query = dns.resolver.query(host)
expiration = query.expiration
addresses = tuple(ipaddress.ip_address(__.address) for __ in query)
except dns.resolver.NXDOMAIN:
expiration = time.time() + NX_EXPIRE
addresses = ()
return int(expiration), addresses
class DNS(dict):
def __init__(self, hosts=None):
hosts = hosts if hosts else ()
data = {host: dns_query(host) for host in hosts}
dict.__init__(self, data)
def __getitem__(self, host):
try:
expiration, addresses = dict.__getitem__(self, host)
if expiration <= int(time.time()):
raise ValueError('DNS query expired')
except (ValueError, KeyError):
expiration, addresses = dns_query(host)
self[host] = expiration, addresses
address = random.choice(addresses) if addresses else None
return address
以上是关于python DNS字典。 __getitem__任何主机,它从系统DNS返回一个随机的ipaddress,表示TTL的主要内容,如果未能解决你的问题,请参考以下文章
Python3基础 __len__,__getitem__ 记录列表中元素访问的次数 定制不可变序列,下标字典
python 学习 有序字典
自定义字典以维护它的 __getitem__ on ** (star-star-unpacking)
pythonitem方法
Python类中的魔法方法
python手记------字典(操作方法)