Skip to content

Commit 35a6ca2

Browse files
committed
checking in cache
1 parent d134ca8 commit 35a6ca2

File tree

2 files changed

+24
-4
lines changed

2 files changed

+24
-4
lines changed

ipinfo/handler.py

Lines changed: 24 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -315,6 +315,7 @@ def getBatchDetailsIter(
315315
if batch_size is None:
316316
batch_size = BATCH_MAX_SIZE
317317

318+
result = {}
318319
lookup_addresses = []
319320
for ip_address in ip_addresses:
320321
if isinstance(ip_address, IPv4Address) or isinstance(
@@ -330,6 +331,27 @@ def getBatchDetailsIter(
330331
else:
331332
lookup_addresses.append(ip_address)
332333

334+
# pre-populate with anything we've got in the cache, and keep around
335+
# the IPs not in the cache.
336+
for ip_address in ip_addresses:
337+
# if the supplied IP address uses the objects defined in the
338+
# built-in module ipaddress extract the appropriate string notation
339+
# before formatting the URL.
340+
if isinstance(ip_address, IPv4Address) or isinstance(
341+
ip_address, IPv6Address
342+
):
343+
ip_address = ip_address.exploded
344+
345+
try:
346+
cached_ipaddr = self.cache[cache_key(ip_address)]
347+
result[ip_address] = cached_ipaddr
348+
except KeyError:
349+
lookup_addresses.append(ip_address)
350+
351+
# all in cache - exit early.
352+
if len(lookup_addresses) == 0:
353+
yield result
354+
333355
url = API_URL + "/batch"
334356
headers = handler_utils.get_headers(self.access_token, self.headers)
335357
headers["content-type"] = "application/json"
@@ -361,6 +383,5 @@ def getBatchDetailsIter(
361383
)
362384
for ip in batch:
363385
detail = details.get(ip)
364-
if detail is not None:
365-
self.cache[cache_key(ip)] = detail
366-
yield detail
386+
self.cache[cache_key(ip)] = detail
387+
yield detail

ipinfo/handler_async.py

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -394,7 +394,6 @@ async def process_batch(batch):
394394
for ip_address, details in json_response.items():
395395
self.cache[cache_key(ip_address)] = details
396396
results[ip_address] = details
397-
398397
except Exception as e:
399398
return handler_utils.return_or_fail(raise_on_fail, e, results)
400399

0 commit comments

Comments
 (0)