Skip to content

Commit

Permalink
Split lookup function into 3 new ones
Browse files Browse the repository at this point in the history
  • Loading branch information
lpellegr committed Jun 10, 2024
1 parent 2564d51 commit 7891f93
Show file tree
Hide file tree
Showing 10 changed files with 43 additions and 43 deletions.
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
## [Unreleased]
### Changed
- Require Python 3.8+.
- Replace the function named `lookup` by 3 new functions: `batch_lookup_ips`, `lookup_ip` and `origin_lookup_ip`.
- Introduce data model for responses to enable field value access using dot notation and ensure code autocompletion functionality.
- Rename all function and variable names to adhere to snake_case convention.
- Rename _IpregistryConfig_ option `apiUrl` to `baseUrl`.
Expand Down
6 changes: 3 additions & 3 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@ pip install ipregistry
from ipregistry import IpregistryClient

client = IpregistryClient("YOUR_API_KEY")
ip_info = client.lookup("54.85.132.205")
ip_info = client.lookup_ip("54.85.132.205")
print(ip_info)
```

Expand All @@ -39,7 +39,7 @@ print(ip_info)
from ipregistry import IpregistryClient

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

client = IpregistryClient("YOUR_API_KEY")
ip_info = client.lookup()
ip_info = client.origin_lookup_ip()
print(ip_info)
```

Expand Down
40 changes: 19 additions & 21 deletions ipregistry/core.py
Original file line number Diff line number Diff line change
Expand Up @@ -30,38 +30,28 @@ def __init__(self, key_or_config, **kwargs):
if not isinstance(self._requestHandler, IpregistryRequestHandler):
raise ValueError("Given request handler instance is not of type IpregistryRequestHandler")

def lookup(self, ip_or_list='', **options):
if ip_or_list == '':
return self._origin_lookup(options)
elif isinstance(ip_or_list, list):
return self._batch_lookup(ip_or_list, options)
elif isinstance(ip_or_list, str):
return self._single_lookup(ip_or_list, options)
else:
raise ValueError("Invalid parameter type")

def _batch_lookup(self, ips, options):
def batch_lookup_ips(self, ips, options):
sparse_cache = [None] * len(ips)
cache_misses = []

for i in range(0, len(ips)):
ip = ips[i]
cache_key = self._build_cache_key(ip, options)
cache_key = self.__build_cache_key(ip, options)
cache_value = self._cache.get(cache_key)
if cache_value is None:
cache_misses.append(ip)
else:
sparse_cache[i] = cache_value

result = [None] * len(ips)
fresh_ip_info = self._requestHandler.batch_lookup(cache_misses, options)
fresh_ip_info = self._requestHandler.batch_lookup_ips(cache_misses, options)
j = 0
k = 0

for cachedIpInfo in sparse_cache:
if cachedIpInfo is None:
if not isinstance(fresh_ip_info[k], LookupError):
self._cache.put(self._build_cache_key(ips[j], options), fresh_ip_info[k])
self._cache.put(self.__build_cache_key(ips[j], options), fresh_ip_info[k])
result[j] = fresh_ip_info[k]
k += 1
else:
Expand All @@ -70,20 +60,27 @@ def _batch_lookup(self, ips, options):

return result

def _origin_lookup(self, options):
return self._single_lookup('', options)
def lookup_ip(self, ip='', **options):
if isinstance(ip, str) and len(ip) > 0:
return self.__lookup_ip(ip, options)
else:
raise ValueError("Invalid value for 'ip' parameter: " + ip)

def origin_lookup_ip(self, **options):
return self.__lookup_ip('', options)

def _single_lookup(self, ip, options):
cache_key = self._build_cache_key(ip, options)
def __lookup_ip(self, ip, options):
cache_key = self.__build_cache_key(ip, options)
cache_value = self._cache.get(cache_key)

if cache_value is None:
cache_value = self._requestHandler.single_lookup(ip, options)
cache_value = self._requestHandler.lookup_ip(ip, options)
self._cache.put(cache_key, cache_value)

return cache_value

def _build_cache_key(self, ip, options):
@staticmethod
def __build_cache_key(ip, options):
result = ip

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

return result

def _is_api_error(self, data):
@staticmethod
def __is_api_error(data):
return 'code' in data


Expand Down
23 changes: 12 additions & 11 deletions ipregistry/request.py
Original file line number Diff line number Diff line change
Expand Up @@ -29,15 +29,15 @@ def __init__(self, config):
self._config = config

@abstractmethod
def batch_lookup(self, ips, options):
def batch_lookup_ips(self, ips, options):
pass

@abstractmethod
def origin_lookup(self, options):
def lookup_ip(self, ip, options):
pass

@abstractmethod
def single_lookup(self, ip, options):
def origin_lookup_ip(self, options):
pass

def _build_base_url(self, ip, options):
Expand All @@ -52,30 +52,31 @@ def _build_base_url(self, ip, options):


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

def origin_lookup(self, options):
return self.single_lookup('', options)

def single_lookup(self, ip, options):
def lookup_ip(self, ip, options):
try:
r = requests.get(self._build_base_url(ip, options), headers=self._headers(), timeout=self._config.timeout)
r = requests.get(self._build_base_url(ip, options), headers=self.__headers(), timeout=self._config.timeout)
r.raise_for_status()
return IpInfo(**r.json())
except requests.HTTPError:
raise ApiError(r.json())
except Exception as e:
raise ClientError(e)

def _headers(self):
def origin_lookup_ip(self, options):
return self.lookup_ip('', options)

@staticmethod
def __headers():
return {
"content-type": "application/json",
"user-agent": "Ipregistry/Python" + str(sys.version_info[0]) + "/" + __version__
Expand Down
2 changes: 1 addition & 1 deletion samples/batch-lookup.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@
try:
apiKey = "tryout"
client = IpregistryClient(apiKey)
ipInfoList = client.lookup(["73.2.2.2", "8.8.8.8", "2001:67c:2e8:22::c100:68b"])
ipInfoList = client.batch_lookup_ips(["73.2.2.2", "8.8.8.8", "2001:67c:2e8:22::c100:68b"])

for lookupResult in ipInfoList:
if isinstance(lookupResult, IpInfo):
Expand Down
2 changes: 1 addition & 1 deletion samples/origin-lookup.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@
try:
apiKey = "tryout"
client = IpregistryClient(apiKey)
ipInfo = client.lookup()
ipInfo = client.origin_lookup_ip()
print(ipInfo)
except ApiError as e:
print("API error", e)
Expand Down
2 changes: 1 addition & 1 deletion samples/single-lookup-nocache.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@
try:
apiKey = "tryout"
client = IpregistryClient(apiKey, cache=NoCache())
ipInfo = client.lookup("54.85.132.205")
ipInfo = client.lookup_ip("54.85.132.205")
print(ipInfo)
except ApiError as e:
print("API error", e)
Expand Down
2 changes: 1 addition & 1 deletion samples/single-lookup-options.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@
try:
apiKey = "tryout"
client = IpregistryClient(apiKey)
ipInfo = client.lookup("54.85.132.205", hostname=True, fields="location.country")
ipInfo = client.lookup_ip("54.85.132.205", hostname=True, fields="location.country")
print(ipInfo)
except ApiError as e:
print("API error", e)
Expand Down
2 changes: 1 addition & 1 deletion samples/single-lookup.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@
try:
apiKey = "tryout"
client = IpregistryClient(apiKey)
ipInfo = client.lookup("54.85.132.205")
ipInfo = client.lookup_ip("54.85.132.205")
print(ipInfo)
except ApiError as e:
print("API error", e)
Expand Down
6 changes: 3 additions & 3 deletions tests/test_client.py
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,7 @@ def test_simple_lookup(self):
Test that a simple lookup returns data
"""
client = IpregistryClient(os.getenv('IPREGISTRY_API_KEY'))
response = client.lookup('8.8.8.8')
response = client.lookup_ip('8.8.8.8')
self.assertIsNotNone(response.ip)
self.assertIsNotNone(response.company.domain)
self.assertEqual('US', response.location.country.code)
Expand All @@ -44,8 +44,8 @@ def test_simple_lookup_in_memory_cache(self):
Test consecutive lookup with in-memory cache
"""
client = IpregistryClient(os.getenv('IPREGISTRY_API_KEY'), cache=InMemoryCache(maxsize=2048, ttl=600))
response = client.lookup('8.8.8.8')
response = client.lookup('8.8.8.8')
response = client.lookup_ip('8.8.8.8')
response = client.lookup_ip('8.8.8.8')
self.assertIsNotNone(response.ip)
self.assertIsNotNone(response.company.domain)

Expand Down

0 comments on commit 7891f93

Please sign in to comment.