perf: 优化使用两个 ip 库

pull/8240/head
ibuler 2022-05-16 12:18:23 +08:00 committed by Jiangjie.Bai
parent 1e6e59d815
commit 2a8f8dd709
9 changed files with 57 additions and 12 deletions

View File

@ -9,4 +9,3 @@ from .crypto import *
from .random import *
from .jumpserver import *
from .ip import *
from .geoip import *

View File

@ -0,0 +1 @@
from .utils import *

View File

@ -8,11 +8,11 @@ from geoip2.errors import GeoIP2Error
from django.utils.translation import ugettext_lazy as _
from django.conf import settings
__all__ = ['get_ip_city']
__all__ = ['get_ip_city_by_geoip']
reader = None
def get_ip_city(ip):
def get_ip_city_by_geoip(ip):
if not ip or '.' not in ip or not isinstance(ip, str):
return _("Invalid ip")
if ':' in ip:
@ -32,15 +32,13 @@ def get_ip_city(ip):
try:
response = reader.city(ip)
except GeoIP2Error:
return _("Unknown ip")
return {}
names = response.city.names
if not names:
names = response.country.names
city_names = response.city.names or {}
lang = settings.LANGUAGE_CODE[:2]
if lang == 'zh':
lang = 'zh-CN'
city = city_names.get(lang, _("Unknown"))
return city
if 'en' in settings.LANGUAGE_CODE and 'en' in names:
return names['en']
elif 'zh-CN' in names:
return names['zh-CN']
return _("Unknown ip")

View File

@ -0,0 +1,3 @@
# -*- coding: utf-8 -*-
#
from .utils import *

View File

@ -0,0 +1,3 @@
version https://git-lfs.github.com/spec/v1
oid sha256:b82b874152c798dda407ffe7544e1f5ec67efa1f5c334efc0d3893b8053b4be1
size 3649897

View File

@ -0,0 +1,23 @@
# -*- coding: utf-8 -*-
#
import os
from django.utils.translation import ugettext as _
import ipdb
__all__ = ['get_ip_city_by_ipip']
ipip_db = None
def get_ip_city_by_ipip(ip):
global ipip_db
if not ip or not isinstance(ip, str):
return _("Invalid ip")
if ':' in ip:
return 'IPv6'
if ipip_db is None:
ipip_db_path = os.path.join(os.path.dirname(__file__), 'ipipfree.ipdb')
ipip_db = ipdb.City(ipip_db_path)
info = ipip_db.find_info(ip, 'CN')
return {'city': info.city_name, 'country': info.country_name}

View File

@ -1,4 +1,9 @@
from ipaddress import ip_network, ip_address
from django.conf import settings
from django.utils.translation import gettext_lazy as _
from .ipip import get_ip_city_by_ipip
from .geoip import get_ip_city_by_geoip
def is_ip_address(address):
@ -66,3 +71,16 @@ def contains_ip(ip, ip_group):
return True
return False
def get_ip_city(ip):
info = get_ip_city_by_ipip(ip)
city = info.get('city', _("Unknown"))
country = info.get('country')
# 国内城市 并且 语言是中文就使用国内
is_zh = settings.LANGUAGE_CODE.startswith('zh')
if country == '中国' and is_zh:
return city
else:
return get_ip_city_by_geoip(ip)