Hopefully fix IP2Location issues

This commit is contained in:
Parker M. 2024-11-03 22:42:22 -06:00
parent e22ef86f07
commit 850c3c7c40
Signed by: parker
GPG Key ID: 505ED36FC12B5D5E

View File

@ -1,15 +1,11 @@
import ip2locationio import requests
import datetime import datetime
from ua_parser import user_agent_parser from ua_parser import user_agent_parser
from ip2locationio.ipgeolocation import IP2LocationIOAPIError
from database import SessionLocal from database import SessionLocal
import config import config
from models import Link, Record from models import Link, Record
configuration = ip2locationio.Configuration(config.API_KEY)
ipgeolocation = ip2locationio.IPGeolocation(configuration)
""" """
Create a new log record whenever a link is visited Create a new log record whenever a link is visited
""" """
@ -28,14 +24,19 @@ def log(link, ip, user_agent):
if config.IP_TO_LOCATION: if config.IP_TO_LOCATION:
# Get IP to GEO via IP2Location.io # Get IP to GEO via IP2Location.io
try: try:
data = ipgeolocation.lookup(ip) url = f"https://api.ip2location.io/?key={config.API_KEY}&ip={ip}"
location = f'{data["country_name"]}, {data["city_name"]}' data = requests.get(url).json()
isp = data["as"] if "error" in data:
# Fatal error, API key is invalid or out of requests, quit raise Exception("Error")
except IP2LocationIOAPIError: else:
location = f'{data["country_name"]}, {data["city"]}'
isp = data["as"]
# Fatal error, maybe API is down?
except:
config.LOG.error( config.LOG.error(
"Invalid API key or insufficient credits. Change the" "Error with IP2Location API. Likely wrong API key or"
" `config.ini` file if you no longer need IP geolocation." " insufficient credits."
) )
location = "-, -" location = "-, -"
isp = "-" isp = "-"