def _validate_ip_name(self, tree):
if any(isinstance(name, IPAddress) and not isinstance(
name.value, (ipaddress.IPv4Network, ipaddress.IPv6Network)
) for name in tree):
raise TypeError(
"IPAddress name constraints must be an IPv4Network or"
" IPv6Network object"
)
python类IPv6Network()的实例源码
def __init__(self, prefix=None, strict=False):
"""Init new Prefix instance."""
if isinstance(prefix, (ipaddress.IPv4Network, ipaddress.IPv6Network)):
self._prefix = prefix
else:
self._prefix = ipaddress.ip_network(prefix, strict=strict)
def _validate_ip_name(self, tree):
if any(isinstance(name, IPAddress) and not isinstance(
name.value, (ipaddress.IPv4Network, ipaddress.IPv6Network)
) for name in tree):
raise TypeError(
"IPAddress name constraints must be an IPv4Network or"
" IPv6Network object"
)
def _validate_ip_name(self, tree):
if any(isinstance(name, IPAddress) and not isinstance(
name.value, (ipaddress.IPv4Network, ipaddress.IPv6Network)
) for name in tree):
raise TypeError(
"IPAddress name constraints must be an IPv4Network or"
" IPv6Network object"
)
def _validate_ip_name(self, tree):
if any(isinstance(name, IPAddress) and not isinstance(
name.value, (ipaddress.IPv4Network, ipaddress.IPv6Network)
) for name in tree):
raise TypeError(
"IPAddress name constraints must be an IPv4Network or"
" IPv6Network object"
)
def _validate_ip_name(self, tree):
if any(isinstance(name, IPAddress) and not isinstance(
name.value, (ipaddress.IPv4Network, ipaddress.IPv6Network)
) for name in tree):
raise TypeError(
"IPAddress name constraints must be an IPv4Network or"
" IPv6Network object"
)
inputtype.py 文件源码
项目:archive-Holmes-Totem-Service-Library
作者: HolmesProcessing
项目源码
文件源码
阅读 23
收藏 0
点赞 0
评论 0
def Detect(_input):
"""
Determine the type of the object and return an integer corresponding to the
global constants Domain, Email, or IP.
Any string input is assumed to be utf-8 encoded and transformed to a bytes
object by calling _input.encode("utf-8") if necessary (domain/email
detection).
Supports IPv4, IPv6 in punctuated string representation or decimal number
(<32 bit is considered IPv4)
-> Return value: ipaddress.IPv4Address or ipaddress.IPv6Address
Supports CIDR IP address range (returns: ipaddress.IPv4Network or
ipaddress.IPv6Network)
Supports Email and "Name <Email>" (returns Email)
Supports Domain (returns the input string)
Supports detection of files (by checking if it is available in /tmp/)
On success returns:
Type(int): Domain, Email, IP, IPNet, File
Parsed Object: Email, ipaddress.ip_address, ipaddress.ip_network, os.Fi
Error: None
On failure returns:
Type(int): Unknown / None (None if EmptyInputError)
Parsed Object: None
Error: EmptyInputError / UnknownTypeError
*Any attempt to detect a domain without a proper TLD map set will
result in a panic!* (see inputtype.InitializeTLDMap(path))
TODO: provide methods to check if an input is a specific type
"""
return __detectType(_input)
def monkey_patch_support_for_python2():
from future import standard_library
standard_library.install_aliases()
# Monkey patch the backported ipaddress module with alternative
# versions that accept string addresses, in addition to unicode
# addresses, in python2 code.
#
# This keep compatibility simple. Slightly complicated by the fact
# that some of these classes inherit from each other.
import ipaddress
def python2_compat(cls, bases=()):
def __init__(self, address, *args, **kwargs):
if isinstance(address, str) and len(address) > 4:
address = address.decode('utf-8')
return cls.__init__(self, address, *args, **kwargs)
return type(cls.__name__, (cls,) + bases, {'__init__': __init__})
ipaddress.IPv4Network = python2_compat(ipaddress.IPv4Network)
ipaddress.IPv4Address = python2_compat(ipaddress.IPv4Address)
ipaddress.IPv4Interface = python2_compat(ipaddress.IPv4Interface,
bases=(ipaddress.IPv4Address,))
ipaddress.IPv6Network = python2_compat(ipaddress.IPv6Network)
ipaddress.IPv6Address = python2_compat(ipaddress.IPv6Address)
ipaddress.IPv6Interface = python2_compat(ipaddress.IPv6Interface,
bases=(ipaddress.IPv6Address,))
def register_ipaddress(conn_or_curs=None):
"""
Register conversion support between `ipaddress` objects and `network types`__.
:param conn_or_curs: the scope where to register the type casters.
If `!None` register them globally.
After the function is called, PostgreSQL :sql:`inet` values will be
converted into `~ipaddress.IPv4Interface` or `~ipaddress.IPv6Interface`
objects, :sql:`cidr` values into into `~ipaddress.IPv4Network` or
`~ipaddress.IPv6Network`.
.. __: https://www.postgresql.org/docs/current/static/datatype-net-types.html
"""
global ipaddress
import ipaddress
global _casters
if _casters is None:
_casters = _make_casters()
for c in _casters:
register_type(c, conn_or_curs)
for t in [ipaddress.IPv4Interface, ipaddress.IPv6Interface,
ipaddress.IPv4Network, ipaddress.IPv6Network]:
register_adapter(t, adapt_ipaddress)
def test_cidr_array_cast(self):
import ipaddress as ip
cur = self.conn.cursor()
psycopg2.extras.register_ipaddress(cur)
cur.execute("select '{NULL,127.0.0.1,::ffff:102:300/128}'::cidr[]")
l = cur.fetchone()[0]
self.assertTrue(l[0] is None)
self.assertEqual(l[1], ip.ip_network('127.0.0.1'))
self.assertEqual(l[2], ip.ip_network('::ffff:102:300/128'))
self.assertTrue(isinstance(l[1], ip.IPv4Network), l)
self.assertTrue(isinstance(l[2], ip.IPv6Network), l)
def register_ipaddress(conn_or_curs=None):
"""
Register conversion support between `ipaddress` objects and `network types`__.
:param conn_or_curs: the scope where to register the type casters.
If `!None` register them globally.
After the function is called, PostgreSQL :sql:`inet` values will be
converted into `~ipaddress.IPv4Interface` or `~ipaddress.IPv6Interface`
objects, :sql:`cidr` values into into `~ipaddress.IPv4Network` or
`~ipaddress.IPv6Network`.
.. __: https://www.postgresql.org/docs/current/static/datatype-net-types.html
"""
global ipaddress
import ipaddress
global _casters
if _casters is None:
_casters = _make_casters()
for c in _casters:
register_type(c, conn_or_curs)
for t in [ipaddress.IPv4Interface, ipaddress.IPv6Interface,
ipaddress.IPv4Network, ipaddress.IPv6Network]:
register_adapter(t, adapt_ipaddress)
def test_cidr_array_cast(self):
import ipaddress as ip
cur = self.conn.cursor()
psycopg2.extras.register_ipaddress(cur)
cur.execute("select '{NULL,127.0.0.1,::ffff:102:300/128}'::cidr[]")
l = cur.fetchone()[0]
self.assert_(l[0] is None)
self.assertEquals(l[1], ip.ip_network('127.0.0.1'))
self.assertEquals(l[2], ip.ip_network('::ffff:102:300/128'))
self.assert_(isinstance(l[1], ip.IPv4Network), l)
self.assert_(isinstance(l[2], ip.IPv6Network), l)
def get_network_object(prefix):
u = prefix.decode('utf8')
try:
return ipaddress.IPv4Network(u, strict=False)
except (ValueError, ipaddress.AddressValueError, ipaddress.NetmaskValueError):
pass
try:
return ipaddress.IPv6Network(u, strict=False)
except (ValueError, ipaddress.AddressValueError, ipaddress.NetmaskValueError):
return None
def setUp(self):
self.ipv4_address = ipaddress.IPv4Address('1.2.3.4')
self.ipv4_interface = ipaddress.IPv4Interface('1.2.3.4/24')
self.ipv4_network = ipaddress.IPv4Network('1.2.3.0/24')
#self.ipv4_hostmask = ipaddress.IPv4Interface('10.0.0.1/0.255.255.255')
self.ipv6_address = ipaddress.IPv6Interface(
'2001:658:22a:cafe:200:0:0:1')
self.ipv6_interface = ipaddress.IPv6Interface(
'2001:658:22a:cafe:200:0:0:1/64')
self.ipv6_network = ipaddress.IPv6Network('2001:658:22a:cafe::/64')
def testGetSupernet(self):
self.assertEqual(self.ipv4_network.supernet().prefixlen, 23)
self.assertEqual(str(self.ipv4_network.supernet().network_address),
'1.2.2.0')
self.assertEqual(
ipaddress.IPv4Interface('0.0.0.0/0').network.supernet(),
ipaddress.IPv4Network('0.0.0.0/0'))
self.assertEqual(self.ipv6_network.supernet().prefixlen, 63)
self.assertEqual(str(self.ipv6_network.supernet().network_address),
'2001:658:22a:cafe::')
self.assertEqual(ipaddress.IPv6Interface('::0/0').network.supernet(),
ipaddress.IPv6Network('::0/0'))
def testGetSubnetForSingle128(self):
ip = ipaddress.IPv6Network('::1/128')
subnets1 = [str(x) for x in ip.subnets()]
subnets2 = [str(x) for x in ip.subnets(2)]
self.assertEqual(subnets1, ['::1/128'])
self.assertEqual(subnets1, subnets2)
def testIpType(self):
ipv4net = ipaddress.ip_network('1.2.3.4')
ipv4addr = ipaddress.ip_address('1.2.3.4')
ipv6net = ipaddress.ip_network('::1.2.3.4')
ipv6addr = ipaddress.ip_address('::1.2.3.4')
self.assertEqual(ipaddress.IPv4Network, type(ipv4net))
self.assertEqual(ipaddress.IPv4Address, type(ipv4addr))
self.assertEqual(ipaddress.IPv6Network, type(ipv6net))
self.assertEqual(ipaddress.IPv6Address, type(ipv6addr))
def testExplodeShortHandIpStr(self):
addr1 = ipaddress.IPv6Interface('2001::1')
addr2 = ipaddress.IPv6Address('2001:0:5ef5:79fd:0:59d:a0e5:ba1')
addr3 = ipaddress.IPv6Network('2001::/96')
addr4 = ipaddress.IPv4Address('192.168.178.1')
self.assertEqual('2001:0000:0000:0000:0000:0000:0000:0001/128',
addr1.exploded)
self.assertEqual('0000:0000:0000:0000:0000:0000:0000:0001/128',
ipaddress.IPv6Interface('::1/128').exploded)
# issue 77
self.assertEqual('2001:0000:5ef5:79fd:0000:059d:a0e5:0ba1',
addr2.exploded)
self.assertEqual('2001:0000:0000:0000:0000:0000:0000:0000/96',
addr3.exploded)
self.assertEqual('192.168.178.1', addr4.exploded)
def _validate_ip_name(self, tree):
if any(isinstance(name, IPAddress) and not isinstance(
name.value, (ipaddress.IPv4Network, ipaddress.IPv6Network)
) for name in tree):
raise TypeError(
"IPAddress name constraints must be an IPv4Network or"
" IPv6Network object"
)
def _validate_ip_name(self, tree):
if any(isinstance(name, IPAddress) and not isinstance(
name.value, (ipaddress.IPv4Network, ipaddress.IPv6Network)
) for name in tree):
raise TypeError(
"IPAddress name constraints must be an IPv4Network or"
" IPv6Network object"
)