mirror of
https://github.com/chubin/wttr.in
synced 2025-01-26 10:45:01 +00:00
Remove cache operation from ip2location; shortcut where possible
This comes with something of a refactor. - IP2LOCATION_KEY 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
This commit is contained in:
parent
628a860d6d
commit
c7d3b32d53
1 changed files with 16 additions and 23 deletions
|
@ -116,30 +116,23 @@ def ipcache(ip_addr):
|
||||||
return None, None
|
return None, None
|
||||||
|
|
||||||
def ip2location(ip_addr):
|
def ip2location(ip_addr):
|
||||||
"Convert IP address `ip_addr` to a location name"
|
"""Convert IP address `ip_addr` to a location name"""
|
||||||
|
# if IP2LOCATION_KEY is not set, do not query,
|
||||||
location = ipcache(ip_addr)
|
|
||||||
if location:
|
|
||||||
return location
|
|
||||||
|
|
||||||
# if IP2LOCATION_KEY is not set, do not the query,
|
|
||||||
# because the query wont be processed anyway
|
# because the query wont be processed anyway
|
||||||
if IP2LOCATION_KEY:
|
if not IP2LOCATION_KEY:
|
||||||
try:
|
return None, None, None
|
||||||
location = requests\
|
try:
|
||||||
.get('http://api.ip2location.com/?ip=%s&key=%s&package=WS3' \
|
r = requests.get(
|
||||||
% (ip_addr, IP2LOCATION_KEY)).text
|
'http://api.ip2location.com/?ip=%s&key=%s&package=WS3'
|
||||||
except requests.exceptions.ConnectionError:
|
% (ip_addr, IP2LOCATION_KEY))
|
||||||
pass
|
r.raise_for_status()
|
||||||
|
location = r.text
|
||||||
if location and ';' in location:
|
if location and ';' in location:
|
||||||
ipcachewrite(ip_addr, location)
|
_, country, region, city = location.split(';')
|
||||||
_, country, region, city = location.split(';')
|
location = city, region, country
|
||||||
location = city, region, country
|
except requests.exceptions.RequestException:
|
||||||
else:
|
return None, None, None
|
||||||
location = location, None, None
|
return city, region, country
|
||||||
|
|
||||||
return location
|
|
||||||
|
|
||||||
|
|
||||||
def ipinfo(ip_addr):
|
def ipinfo(ip_addr):
|
||||||
|
|
Loading…
Reference in a new issue