11#!/usr/bin/env python3
22# -*- coding: utf-8 -*-
33import httpx
4+ from XdbSearchIP .xdbSearcher import XdbSearcher
45from httpx import HTTPError
56from fastapi import Request
67
8+ from backend .app .core .path_conf import IP2REGION_XDB
9+
710
811async def get_request_ip (request : Request ) -> str :
9- """获取请求的ip地址 """
12+ """获取请求的 ip 地址 """
1013 real = request .headers .get ('X-Real-IP' )
1114 if real :
1215 ip = real
@@ -19,8 +22,14 @@ async def get_request_ip(request: Request) -> str:
1922 return ip
2023
2124
22- async def get_location (ipaddr : str , user_agent : str ) -> str :
23- """获取ip地址归属地(临时)"""
25+ async def get_location_online (ipaddr : str , user_agent : str ) -> str :
26+ """
27+ 在线获取 ip 地址属地,无法保证可用性,准确率较高
28+
29+ :param ipaddr:
30+ :param user_agent:
31+ :return:
32+ """
2433 async with httpx .AsyncClient (timeout = 3 ) as client :
2534 ip_api_url = f'http://ip-api.com/json/{ ipaddr } ?lang=zh-CN'
2635 whois_url = f'http://whois.pconline.com.cn/ipJson.jsp?ip={ ipaddr } &json=true'
@@ -35,3 +44,21 @@ async def get_location(ipaddr: str, user_agent: str) -> str:
3544 except (HTTPError , KeyError ):
3645 city = None
3746 return city or '未知' if city != '' else '未知'
47+
48+
49+ def get_location_offline (ipaddr : str ) -> str :
50+ """
51+ 离线获取 ip 地址属地,无法保证准确率,100%可用
52+
53+ :param ipaddr:
54+ :return:
55+ """
56+ cb = XdbSearcher .loadContentFromFile (dbfile = IP2REGION_XDB )
57+ searcher = XdbSearcher (contentBuff = cb )
58+ data = searcher .search (ipaddr )
59+ searcher .close ()
60+ location_info = data .split ('|' )
61+ country = location_info [0 ]
62+ province = location_info [2 ]
63+ city = location_info [3 ]
64+ return city if city != '0' else province if province != '0' else country if country != '0' else '未知'
0 commit comments