Эх сурвалжийг харах

修复GeoIP2保存ip城市信息问题

locky 1 жил өмнө
parent
commit
aae07bbd57

+ 20 - 3
Object/IPWeatherObject.py

@@ -9,6 +9,7 @@ import requests
 from Model.models import IPAddr
 from Object.RedisObject import RedisObject
 from Service.CommonService import CommonService
+from Ansjer.config import LOGGER
 
 
 class IPQuery:
@@ -117,8 +118,24 @@ class GeoIP2:
                 # 经纬度精确到小数点两位
                 lat = round(response.location.latitude, 2)
                 lon = round(response.location.longitude, 2)
-                city = response.city.names['zh-CN']
-                region = response.subdivisions[0].names['zh-CN']
+
+                # 获取中文或英文城市名,省/州
+                city = ''
+                city_names = response.city.names
+                city_cn = city_names.get('zh-CN')
+                if city_cn:
+                    city = city_cn
+                elif city_names.get('en'):
+                    city = city_names['en']
+
+                region = ''
+                subdivisions_names = response.subdivisions[0].names
+                region_cn = subdivisions_names.get('zh-CN')
+                if region_cn:
+                    region = region_cn
+                elif subdivisions_names.get('en'):
+                    region = subdivisions_names['en']
+
                 country_code = response.country.iso_code
 
                 # 保存ip信息
@@ -134,7 +151,7 @@ class GeoIP2:
                 IPAddr.objects.create(**ip_addr_data)
 
         except Exception as e:
-            print('error_line:{}, error_msg:{}'.format(e.__traceback__.tb_lineno, repr(e)))
+            LOGGER.info('GeoIP2解析ip异常:error_line:{}, error_msg:{}'.format(e.__traceback__.tb_lineno, repr(e)))
 
 
 class OpenWeatherMap: