Skip to content

Commit 904bee0

Browse files
committed
impl async for single req
1 parent b043b50 commit 904bee0

File tree

1 file changed

+15
-10
lines changed

1 file changed

+15
-10
lines changed

ipinfo/handler_async.py

Lines changed: 15 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -95,19 +95,21 @@ async def getDetails(self, ip_address=None):
9595
if ip_address in self.cache:
9696
return Details(self.cache[ip_address])
9797

98-
# not in cache; get result, format it, and put in cache.
98+
# not in cache; do http req
9999
url = self.API_URL
100100
if ip_address:
101101
url += "/" + ip_address
102-
response = requests.get(
103-
url, headers=self._get_headers(), **self.request_options
104-
)
105-
if response.status_code == 429:
106-
raise RequestQuotaExceededError()
107-
response.raise_for_status()
108-
raw_details = response.json()
102+
headers = self._get_headers()
103+
async with self.httpsess.get(url, headers=headers) as resp:
104+
if resp.status == 429:
105+
raise RequestQuotaExceededError()
106+
resp.raise_for_status()
107+
raw_details = await resp.json()
108+
109+
# format & cache
109110
self._format_details(raw_details)
110111
self.cache[ip_address] = raw_details
112+
111113
return Details(raw_details)
112114

113115
async def getBatchDetails(self, ip_addresses):
@@ -162,8 +164,11 @@ async def getBatchDetails(self, ip_addresses):
162164

163165
def _ensure_aiohttp_ready(self):
164166
"""Ensures aiohttp internal state is initialized."""
165-
if not self.httpsess:
166-
self.httpsess = aiohttp.ClientSession()
167+
if self.httpsess:
168+
return
169+
170+
timeout = aiohttp.ClientTimeout(total=self.request_options["timeout"])
171+
self.httpsess = aiohttp.ClientSession(timeout=timeout)
167172

168173
def _get_headers(self):
169174
"""Built headers for request to IPinfo API."""

0 commit comments

Comments
 (0)