Skip to content

Commit 023a15c

Browse files
authored
Merge pull request #23 from bartbroere/feature/allow-builtin-ipaddress
Allow supplying IP address from the builtin ipaddress module
2 parents da47d76 + bd5e516 commit 023a15c

File tree

2 files changed

+29
-0
lines changed

2 files changed

+29
-0
lines changed

ipinfo/handler.py

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@
22
Main API client handler for fetching data from the IPinfo service.
33
"""
44

5+
from ipaddress import IPv4Address, IPv6Address
56
import json
67
import os
78
import sys
@@ -57,6 +58,11 @@ def getBatchDetails(self, ip_addresses):
5758
# the IPs not in the cache.
5859
lookup_addresses = []
5960
for ip_address in ip_addresses:
61+
# If the supplied IP address uses the objects defined in the built-in module ipaddress
62+
# extract the appropriate string notation before formatting the URL
63+
if isinstance(ip_address, IPv4Address) or isinstance(ip_address, IPv6Address):
64+
ip_address = ip_address.exploded
65+
6066
if ip_address in self.cache:
6167
result[ip_address] = self.cache[ip_address]
6268
else:
@@ -90,6 +96,12 @@ def getBatchDetails(self, ip_addresses):
9096

9197
def _requestDetails(self, ip_address=None):
9298
"""Get IP address data by sending request to IPinfo API."""
99+
100+
# If the supplied IP address uses the objects defined in the built-in module ipaddress
101+
# extract the appropriate string notation before formatting the URL
102+
if isinstance(ip_address, IPv4Address) or isinstance(ip_address, IPv6Address):
103+
ip_address = ip_address.exploded
104+
93105
if ip_address not in self.cache:
94106
url = self.API_URL
95107
if ip_address:

tests/handler_test.py

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
1+
from ipaddress import IPv4Address
12
import json
23

34
from ipinfo.cache.default import DefaultCache
@@ -39,6 +40,22 @@ def test_get_details():
3940
assert details.latitude == "12.34"
4041

4142

43+
def test_builtin_ip_types():
44+
handler = Handler()
45+
fake_details = {"country": "US", "ip": "127.0.0.1", "loc": "12.34,56.78"}
46+
47+
handler._requestDetails = lambda x: fake_details
48+
49+
details = handler.getDetails(IPv4Address(fake_details["ip"]))
50+
assert isinstance(details, Details)
51+
assert details.country == fake_details["country"]
52+
assert details.country_name == "United States"
53+
assert details.ip == fake_details["ip"]
54+
assert details.loc == fake_details["loc"]
55+
assert details.longitude == "56.78"
56+
assert details.latitude == "12.34"
57+
58+
4259
def test_json_serialization():
4360
handler = Handler()
4461
fake_details = {

0 commit comments

Comments
 (0)