From 7891f937287f4e00a3e662fb61949501d7d43301 Mon Sep 17 00:00:00 2001 From: Laurent Pellegrino Date: Mon, 10 Jun 2024 22:03:37 +0200 Subject: [PATCH] Split lookup function into 3 new ones --- CHANGELOG.md | 1 + README.md | 6 ++--- ipregistry/core.py | 40 +++++++++++++++----------------- ipregistry/request.py | 23 +++++++++--------- samples/batch-lookup.py | 2 +- samples/origin-lookup.py | 2 +- samples/single-lookup-nocache.py | 2 +- samples/single-lookup-options.py | 2 +- samples/single-lookup.py | 2 +- tests/test_client.py | 6 ++--- 10 files changed, 43 insertions(+), 43 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 75cc0bb..a899cf7 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -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`. diff --git a/README.md b/README.md index 2d88ca5..d40c9c0 100644 --- a/README.md +++ b/README.md @@ -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) ``` @@ -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) ``` @@ -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) ``` diff --git a/ipregistry/core.py b/ipregistry/core.py index b53e8a3..1465aa7 100644 --- a/ipregistry/core.py +++ b/ipregistry/core.py @@ -30,23 +30,13 @@ 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) @@ -54,14 +44,14 @@ def _batch_lookup(self, ips, options): 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: @@ -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(): @@ -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 diff --git a/ipregistry/request.py b/ipregistry/request.py index 07b4170..8764a42 100644 --- a/ipregistry/request.py +++ b/ipregistry/request.py @@ -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): @@ -52,9 +52,9 @@ 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: @@ -62,12 +62,9 @@ def batch_lookup(self, ips, options): 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: @@ -75,7 +72,11 @@ def single_lookup(self, ip, options): 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__ diff --git a/samples/batch-lookup.py b/samples/batch-lookup.py index 375c2ce..e487e73 100644 --- a/samples/batch-lookup.py +++ b/samples/batch-lookup.py @@ -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): diff --git a/samples/origin-lookup.py b/samples/origin-lookup.py index e32861a..ca6102e 100644 --- a/samples/origin-lookup.py +++ b/samples/origin-lookup.py @@ -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) diff --git a/samples/single-lookup-nocache.py b/samples/single-lookup-nocache.py index 4bdc265..bdf58d5 100644 --- a/samples/single-lookup-nocache.py +++ b/samples/single-lookup-nocache.py @@ -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) diff --git a/samples/single-lookup-options.py b/samples/single-lookup-options.py index cc57aa8..d90f24d 100644 --- a/samples/single-lookup-options.py +++ b/samples/single-lookup-options.py @@ -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) diff --git a/samples/single-lookup.py b/samples/single-lookup.py index fb4b34c..04853bc 100644 --- a/samples/single-lookup.py +++ b/samples/single-lookup.py @@ -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) diff --git a/tests/test_client.py b/tests/test_client.py index c784644..a20e1e4 100644 --- a/tests/test_client.py +++ b/tests/test_client.py @@ -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) @@ -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)