Skip to content

Commit

Permalink
Merge pull request #93 from ProgramR4732/patch-2
Browse files Browse the repository at this point in the history
optimized sub-optimal code.
  • Loading branch information
UmanShahzad authored Nov 5, 2023
2 parents 06dea5e + cd54bfe commit 5236852
Showing 1 changed file with 13 additions and 20 deletions.
33 changes: 13 additions & 20 deletions ipinfo/handler_async.py
Original file line number Diff line number Diff line change
Expand Up @@ -141,9 +141,7 @@ async def getDetails(self, ip_address=None, timeout=None):

# check if bogon.
if ip_address and is_bogon(ip_address):
details = {}
details["ip"] = ip_address
details["bogon"] = True
details = {"ip": ip_address, "bogon": True}
return Details(details)

# check cache first.
Expand Down Expand Up @@ -225,7 +223,7 @@ async def getBatchDetails(
"""
self._ensure_aiohttp_ready()

if batch_size == None:
if batch_size is None:
batch_size = BATCH_MAX_SIZE

result = {}
Expand All @@ -249,7 +247,7 @@ async def getBatchDetails(
lookup_addresses.append(ip_address)

# all in cache - return early.
if len(lookup_addresses) == 0:
if not lookup_addresses:
return result

# do start timer if necessary
Expand Down Expand Up @@ -282,7 +280,7 @@ async def getBatchDetails(
)

# if all done, return result.
if len(pending) == 0:
if not pending:
return result

# if some had a timeout, first cancel timed out stuff and wait for
Expand Down Expand Up @@ -370,9 +368,7 @@ async def getBatchDetailsIter(
ip_address = ip_address.exploded

if ip_address and is_bogon(ip_address):
details = {}
details["ip"] = ip_address
details["bogon"] = True
details = {"ip": ip_address, "bogon": True}
yield Details(details)
else:
lookup_addresses.append(ip_address)
Expand All @@ -383,24 +379,21 @@ async def getBatchDetailsIter(
except KeyError:
lookup_addresses.append(ip_address)

if len(lookup_addresses) == 0:
if not lookup_addresses:
yield results.items()

url = API_URL + "/batch"
headers = handler_utils.get_headers(self.access_token, self.headers)
headers["content-type"] = "application/json"

async def process_batch(batch):
try:
async with aiohttp.ClientSession(headers=headers) as session:
response = await session.post(url, json=batch)
response.raise_for_status()
json_response = await response.json()
for ip_address, details in json_response.items():
self.cache[cache_key(ip_address)] = details
results[ip_address] = details
except Exception as e:
raise e
async with aiohttp.ClientSession(headers=headers) as session:
response = await session.post(url, json=batch)
response.raise_for_status()
json_response = await response.json()
for ip_address, details in json_response.items():
self.cache[cache_key(ip_address)] = details
results[ip_address] = details

for i in range(0, len(lookup_addresses), batch_size):
batch = lookup_addresses[i : i + batch_size]
Expand Down

0 comments on commit 5236852

Please sign in to comment.