From 628a860d6d51ae92dd5595991d8c9d3f1cf11b0c Mon Sep 17 00:00:00 2001 From: Gregory Danielson Date: Sun, 1 Nov 2020 16:32:13 -0600 Subject: [PATCH] Remove cache operation from ipinfo; shortcut where possible This comes with something of a refactor. - IPINFO_TOKEN is now checked with `if not` to reduce indention - ConnectionError is increased to RequestException to catch all requests errors - On that note, now raising for status too - Now catching ValueError in case of json parsing failure --- lib/location.py | 27 +++++++++++++-------------- 1 file changed, 13 insertions(+), 14 deletions(-) diff --git a/lib/location.py b/lib/location.py index a76ce26..888346d 100644 --- a/lib/location.py +++ b/lib/location.py @@ -143,20 +143,19 @@ def ip2location(ip_addr): def ipinfo(ip_addr): - location = ipcache(ip_addr) - if location: - return location - if IPINFO_TOKEN: - r = requests.get('https://ipinfo.io/%s/json?token=%s' % - (ip_addr, IPINFO_TOKEN)) - if r.status_code == 200: - r_json = r.json() - location = r_json["city"], r_json["region"], r_json["country"] - else: - location = None, None, None - if location: - ipcachewrite(ip_addr, location) - return location + if not IPINFO_TOKEN: + return None, None, None + try: + r = requests.get( + 'https://ipinfo.io/%s/json?token=%s' + % (ip_addr, IPINFO_TOKEN)) + r.raise_for_status() + r_json = r.json() + city, region, country = r_json["city"], r_json["region"], r_json["country"] + except (requests.exceptions.RequestException, ValueError): + # latter is thrown by failure to parse json in reponse + return None, None, None + return city, region, country def geoip(ip_addr):