Skip to content

Commit 7891f93

Browse files
Split lookup function into 3 new ones
1 parent 2564d51 commit 7891f93

File tree

10 files changed

+43
-43
lines changed

10 files changed

+43
-43
lines changed

CHANGELOG.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
88
## [Unreleased]
99
### Changed
1010
- Require Python 3.8+.
11+
- Replace the function named `lookup` by 3 new functions: `batch_lookup_ips`, `lookup_ip` and `origin_lookup_ip`.
1112
- Introduce data model for responses to enable field value access using dot notation and ensure code autocompletion functionality.
1213
- Rename all function and variable names to adhere to snake_case convention.
1314
- Rename _IpregistryConfig_ option `apiUrl` to `baseUrl`.

README.md

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -29,7 +29,7 @@ pip install ipregistry
2929
from ipregistry import IpregistryClient
3030

3131
client = IpregistryClient("YOUR_API_KEY")
32-
ip_info = client.lookup("54.85.132.205")
32+
ip_info = client.lookup_ip("54.85.132.205")
3333
print(ip_info)
3434
```
3535

@@ -39,7 +39,7 @@ print(ip_info)
3939
from ipregistry import IpregistryClient
4040

4141
client = IpregistryClient("YOUR_API_KEY")
42-
results = client.lookup(["54.85.132.205", "8.8.8.8", "2001:67c:2e8:22::c100:68b"])
42+
results = client.batch_lookup_ips(["54.85.132.205", "8.8.8.8", "2001:67c:2e8:22::c100:68b"])
4343
for ip_info in results:
4444
print(ip_info)
4545
```
@@ -50,7 +50,7 @@ for ip_info in results:
5050
from ipregistry import IpregistryClient
5151

5252
client = IpregistryClient("YOUR_API_KEY")
53-
ip_info = client.lookup()
53+
ip_info = client.origin_lookup_ip()
5454
print(ip_info)
5555
```
5656

ipregistry/core.py

Lines changed: 19 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -30,38 +30,28 @@ def __init__(self, key_or_config, **kwargs):
3030
if not isinstance(self._requestHandler, IpregistryRequestHandler):
3131
raise ValueError("Given request handler instance is not of type IpregistryRequestHandler")
3232

33-
def lookup(self, ip_or_list='', **options):
34-
if ip_or_list == '':
35-
return self._origin_lookup(options)
36-
elif isinstance(ip_or_list, list):
37-
return self._batch_lookup(ip_or_list, options)
38-
elif isinstance(ip_or_list, str):
39-
return self._single_lookup(ip_or_list, options)
40-
else:
41-
raise ValueError("Invalid parameter type")
42-
43-
def _batch_lookup(self, ips, options):
33+
def batch_lookup_ips(self, ips, options):
4434
sparse_cache = [None] * len(ips)
4535
cache_misses = []
4636

4737
for i in range(0, len(ips)):
4838
ip = ips[i]
49-
cache_key = self._build_cache_key(ip, options)
39+
cache_key = self.__build_cache_key(ip, options)
5040
cache_value = self._cache.get(cache_key)
5141
if cache_value is None:
5242
cache_misses.append(ip)
5343
else:
5444
sparse_cache[i] = cache_value
5545

5646
result = [None] * len(ips)
57-
fresh_ip_info = self._requestHandler.batch_lookup(cache_misses, options)
47+
fresh_ip_info = self._requestHandler.batch_lookup_ips(cache_misses, options)
5848
j = 0
5949
k = 0
6050

6151
for cachedIpInfo in sparse_cache:
6252
if cachedIpInfo is None:
6353
if not isinstance(fresh_ip_info[k], LookupError):
64-
self._cache.put(self._build_cache_key(ips[j], options), fresh_ip_info[k])
54+
self._cache.put(self.__build_cache_key(ips[j], options), fresh_ip_info[k])
6555
result[j] = fresh_ip_info[k]
6656
k += 1
6757
else:
@@ -70,20 +60,27 @@ def _batch_lookup(self, ips, options):
7060

7161
return result
7262

73-
def _origin_lookup(self, options):
74-
return self._single_lookup('', options)
63+
def lookup_ip(self, ip='', **options):
64+
if isinstance(ip, str) and len(ip) > 0:
65+
return self.__lookup_ip(ip, options)
66+
else:
67+
raise ValueError("Invalid value for 'ip' parameter: " + ip)
68+
69+
def origin_lookup_ip(self, **options):
70+
return self.__lookup_ip('', options)
7571

76-
def _single_lookup(self, ip, options):
77-
cache_key = self._build_cache_key(ip, options)
72+
def __lookup_ip(self, ip, options):
73+
cache_key = self.__build_cache_key(ip, options)
7874
cache_value = self._cache.get(cache_key)
7975

8076
if cache_value is None:
81-
cache_value = self._requestHandler.single_lookup(ip, options)
77+
cache_value = self._requestHandler.lookup_ip(ip, options)
8278
self._cache.put(cache_key, cache_value)
8379

8480
return cache_value
8581

86-
def _build_cache_key(self, ip, options):
82+
@staticmethod
83+
def __build_cache_key(ip, options):
8784
result = ip
8885

8986
for key, value in options.items():
@@ -93,7 +90,8 @@ def _build_cache_key(self, ip, options):
9390

9491
return result
9592

96-
def _is_api_error(self, data):
93+
@staticmethod
94+
def __is_api_error(data):
9795
return 'code' in data
9896

9997

ipregistry/request.py

Lines changed: 12 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -29,15 +29,15 @@ def __init__(self, config):
2929
self._config = config
3030

3131
@abstractmethod
32-
def batch_lookup(self, ips, options):
32+
def batch_lookup_ips(self, ips, options):
3333
pass
3434

3535
@abstractmethod
36-
def origin_lookup(self, options):
36+
def lookup_ip(self, ip, options):
3737
pass
3838

3939
@abstractmethod
40-
def single_lookup(self, ip, options):
40+
def origin_lookup_ip(self, options):
4141
pass
4242

4343
def _build_base_url(self, ip, options):
@@ -52,30 +52,31 @@ def _build_base_url(self, ip, options):
5252

5353

5454
class DefaultRequestHandler(IpregistryRequestHandler):
55-
def batch_lookup(self, ips, options):
55+
def batch_lookup_ips(self, ips, options):
5656
try:
57-
r = requests.post(self._build_base_url('', options), data=json.dumps(ips), headers=self._headers(), timeout=self._config.timeout)
57+
r = requests.post(self._build_base_url('', options), data=json.dumps(ips), headers=self.__headers(), timeout=self._config.timeout)
5858
r.raise_for_status()
5959
return list(map(lambda data: LookupError(data) if 'code' in data else IpInfo(**data), r.json()['results']))
6060
except requests.HTTPError:
6161
raise ApiError(r.json())
6262
except Exception as e:
6363
raise ClientError(e)
6464

65-
def origin_lookup(self, options):
66-
return self.single_lookup('', options)
67-
68-
def single_lookup(self, ip, options):
65+
def lookup_ip(self, ip, options):
6966
try:
70-
r = requests.get(self._build_base_url(ip, options), headers=self._headers(), timeout=self._config.timeout)
67+
r = requests.get(self._build_base_url(ip, options), headers=self.__headers(), timeout=self._config.timeout)
7168
r.raise_for_status()
7269
return IpInfo(**r.json())
7370
except requests.HTTPError:
7471
raise ApiError(r.json())
7572
except Exception as e:
7673
raise ClientError(e)
7774

78-
def _headers(self):
75+
def origin_lookup_ip(self, options):
76+
return self.lookup_ip('', options)
77+
78+
@staticmethod
79+
def __headers():
7980
return {
8081
"content-type": "application/json",
8182
"user-agent": "Ipregistry/Python" + str(sys.version_info[0]) + "/" + __version__

samples/batch-lookup.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -19,7 +19,7 @@
1919
try:
2020
apiKey = "tryout"
2121
client = IpregistryClient(apiKey)
22-
ipInfoList = client.lookup(["73.2.2.2", "8.8.8.8", "2001:67c:2e8:22::c100:68b"])
22+
ipInfoList = client.batch_lookup_ips(["73.2.2.2", "8.8.8.8", "2001:67c:2e8:22::c100:68b"])
2323

2424
for lookupResult in ipInfoList:
2525
if isinstance(lookupResult, IpInfo):

samples/origin-lookup.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -19,7 +19,7 @@
1919
try:
2020
apiKey = "tryout"
2121
client = IpregistryClient(apiKey)
22-
ipInfo = client.lookup()
22+
ipInfo = client.origin_lookup_ip()
2323
print(ipInfo)
2424
except ApiError as e:
2525
print("API error", e)

samples/single-lookup-nocache.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -19,7 +19,7 @@
1919
try:
2020
apiKey = "tryout"
2121
client = IpregistryClient(apiKey, cache=NoCache())
22-
ipInfo = client.lookup("54.85.132.205")
22+
ipInfo = client.lookup_ip("54.85.132.205")
2323
print(ipInfo)
2424
except ApiError as e:
2525
print("API error", e)

samples/single-lookup-options.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -19,7 +19,7 @@
1919
try:
2020
apiKey = "tryout"
2121
client = IpregistryClient(apiKey)
22-
ipInfo = client.lookup("54.85.132.205", hostname=True, fields="location.country")
22+
ipInfo = client.lookup_ip("54.85.132.205", hostname=True, fields="location.country")
2323
print(ipInfo)
2424
except ApiError as e:
2525
print("API error", e)

samples/single-lookup.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -19,7 +19,7 @@
1919
try:
2020
apiKey = "tryout"
2121
client = IpregistryClient(apiKey)
22-
ipInfo = client.lookup("54.85.132.205")
22+
ipInfo = client.lookup_ip("54.85.132.205")
2323
print(ipInfo)
2424
except ApiError as e:
2525
print("API error", e)

tests/test_client.py

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -34,7 +34,7 @@ def test_simple_lookup(self):
3434
Test that a simple lookup returns data
3535
"""
3636
client = IpregistryClient(os.getenv('IPREGISTRY_API_KEY'))
37-
response = client.lookup('8.8.8.8')
37+
response = client.lookup_ip('8.8.8.8')
3838
self.assertIsNotNone(response.ip)
3939
self.assertIsNotNone(response.company.domain)
4040
self.assertEqual('US', response.location.country.code)
@@ -44,8 +44,8 @@ def test_simple_lookup_in_memory_cache(self):
4444
Test consecutive lookup with in-memory cache
4545
"""
4646
client = IpregistryClient(os.getenv('IPREGISTRY_API_KEY'), cache=InMemoryCache(maxsize=2048, ttl=600))
47-
response = client.lookup('8.8.8.8')
48-
response = client.lookup('8.8.8.8')
47+
response = client.lookup_ip('8.8.8.8')
48+
response = client.lookup_ip('8.8.8.8')
4949
self.assertIsNotNone(response.ip)
5050
self.assertIsNotNone(response.company.domain)
5151

0 commit comments

Comments
 (0)