最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

Python如何通過ip2region解析IP獲得地域信息

 更新時間:2022年11月30日 10:57:47   作者:億萬行代碼的夢  
這篇文章主要介紹了Python如何通過ip2region解析IP獲得地域信息,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教

通過ip2region解析IP獲得地域信息

目標(biāo),從給的讀取給的ip地址文件解析出ip地域名并輸出CSV文件,我選用的是開源ip2region。ip2region地址

下載好后直接用pycharm打開,因為我用的是python所以其他語言我就忽略了。

這里我對代碼進行了編輯從而實現(xiàn)自己的目的。


主要對benchmark.py進行了修改。

代碼如下:

import threading
import time, sys

from ip2Region import Ip2Region

class BenchmarkThread(threading.Thread):
    __searcher = None
    __lock = None

    def __init__(self, searcher, lock):
        self.__searcher = searcher
        self.__lock = lock
        threading.Thread.__init__(self)

    def run(self):
    	#輸入路徑,每行為一個IP地址
        for IP in open("D:\****\****.txt"):
            self.__lock.acquire()
            try:
                data = self.__searcher.memorySearch(IP)
                region=str(data["region"].decode('utf-8'))
                #print(region.split("|"))
                city=""
                province=""
                regions=region.split("|")
                if(regions[3]=="0"):
                    city=""
                else:
                    city=regions[3]

                if (regions[2] == "0"):
                    province = ""
                else:
                    province = regions[2]
print(IP.strip()+","+regions[0]+province+city+regions[4])
                result=IP.strip()+","+regions[0]+province+city+" "+regions[4]
                with open('*****.csv', 'a') as f:  # 設(shè)置文件對象
                    f.write(result+"\n")

            finally:
                self.__lock.release()

if __name__ == "__main__":
    dbFile = "D:\pythonProject\hx_hdfs_local\ip2region-master\data\ip2region.db"
    if ( len(sys.argv) > 2 ):
        dbFile = sys.argv[1];

    threads = []
    searcher = Ip2Region(dbFile)
    lock = threading.Lock()

    for i in range(1):
        t = BenchmarkThread(searcher, lock)
        threads.append(t)

    sTime = time.time() * 1
    for t in threads:
        t.start()

    for t in threads:
        t.join()
    eTime = time.time() * 1

    #print("Benchmark done: %5f" % (eTime - sTime))

結(jié)果對比:


原始數(shù)據(jù)


結(jié)果數(shù)據(jù)

ip2region的使用總結(jié)

ip2region 簡介

根據(jù)它獲取一個具體ip的信息,通過IP解析出國家、具體地址、網(wǎng)絡(luò)服務(wù)商等相關(guān)信息。

ip2region 實際應(yīng)用

在開發(fā)中,我們需要記錄登陸的日志信息,關(guān)于登陸者的ip和位置信息,可以通過ip2region來實現(xiàn)。

Spring Boot集成ip2region

第一步:pom.xml引入

?? ?<properties>
?? ??? ?<ip2region.version>1.7.2</ip2region.version>
?? ?</properties>
?
? ?<dependency>
?? ??? ?<groupId>org.lionsoul</groupId>
?? ??? ?<artifactId>ip2region</artifactId>
?? ??? ?<version>${ip2region.version}</version>
?? ?</dependency>

第二步:下載ip2region.db

$ git clone https://gitee.com/lionsoul/ip2region.git

下載這個項目之后到data/文件夾下面找到ip2region.db復(fù)制到項目resources下

下載這個項目之后到data/文件夾下面找到ip2region.db復(fù)制到項目resources下

第三步:ip2region 工具類

功能:主要基于IP獲取當(dāng)前位置信息。

import org.apache.commons.io.IOUtils;
import org.lionsoul.ip2region.DataBlock;
import org.lionsoul.ip2region.DbConfig;
import org.lionsoul.ip2region.DbSearcher;
import org.lionsoul.ip2region.Util;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.io.ClassPathResource;
 
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.Method;
 
/**
 * @author zhouzhiwengang
 */
public class AddressUtil {
 
    private static Logger log = LoggerFactory.getLogger(AddressUtil.class);
 
    @SuppressWarnings("all")
    public static String getCityInfo(String ip) {
        //db
        String dbPath = AddressUtil.class.getResource("/ip2region/ip2region.db").getPath();
        File file = new File(dbPath);
 
        if (!file.exists()) {
            log.info("地址庫文件不存在,進行其他處理");
            String tmpDir = System.getProperties().getProperty("java.io.tmpdir");
            dbPath = tmpDir + File.separator + "ip2region.db";
            log.info("臨時文件路徑:{}", dbPath);
            file = new File(dbPath);
            if (!file.exists() || (System.currentTimeMillis() - file.lastModified() > 86400000L)) {
                log.info("文件不存在或者文件存在時間超過1天進入...");
                try {
                    InputStream inputStream = new ClassPathResource("ip2region/ip2region.db").getInputStream();
                    IOUtils.copy(inputStream, new FileOutputStream(file));
                } catch (IOException exception) {
                    exception.printStackTrace();
                }
            }
        }
 
        //查詢算法
        int algorithm = DbSearcher.BTREE_ALGORITHM; //B-tree
        try {
            DbConfig config = new DbConfig();
            DbSearcher searcher = new DbSearcher(config, dbPath);
            //define the method
            Method method = null;
            switch (algorithm) {
                case DbSearcher.BTREE_ALGORITHM:
                    method = searcher.getClass().getMethod("btreeSearch", String.class);
                    break;
                case DbSearcher.BINARY_ALGORITHM:
                    method = searcher.getClass().getMethod("binarySearch", String.class);
                    break;
                case DbSearcher.MEMORY_ALGORITYM:
                    method = searcher.getClass().getMethod("memorySearch", String.class);
                    break;
            }
            DataBlock dataBlock = null;
            if (Util.isIpAddress(ip) == false) {
                log.error("Error: Invalid ip address");
            }
            dataBlock = (DataBlock) method.invoke(searcher, ip);
            return dataBlock.getRegion();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
}

知識拓展

遇到的問題:由于AddressUtil.java 工具類是處于項目common(基礎(chǔ)通用模塊),但部署到tomcat 容器中,提示無法加載ip2region.db 數(shù)據(jù)庫資源文件。

產(chǎn)生上述問題的原因是:項目common(基礎(chǔ)通用模塊)沒有把resources 資源文件夾下的相關(guān)資源打包,僅需要將ip2region.db 打包之項目common(基礎(chǔ)通用模塊).jar 中即可。

解決辦法:改造項目common(基礎(chǔ)通用模塊)的pom.xml 文件,添加如下代碼片段:

<build>
		<resources>
			<resource>
				<directory>src/main/java</directory>
				<includes>
					<include>**/*.xml</include>
				</includes>
			</resource>
			<resource>
				<directory>src/main/resources</directory>
				<includes>
					<include>**.*</include>
					<include>**/*.*</include><!-- i18n能讀取到 -->
					<include>**/*/*.*</include>
				</includes>
			</resource>
		</resources>
	</build>

以上為個人經(jīng)驗,希望能給大家一個參考,也希望大家多多支持腳本之家。

相關(guān)文章

  • python數(shù)據(jù)持久存儲 pickle模塊的基本使用方法解析

    python數(shù)據(jù)持久存儲 pickle模塊的基本使用方法解析

    這篇文章主要介紹了python數(shù)據(jù)持久存儲 pickle模塊的基本使用方法解析,文中通過示例代碼介紹的非常詳細,對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友可以參考下
    2019-08-08
  • 給Python學(xué)習(xí)者的文件讀寫指南(含基礎(chǔ)與進階)

    給Python學(xué)習(xí)者的文件讀寫指南(含基礎(chǔ)與進階)

    今天,貓貓跟大家一起,好好學(xué)習(xí)Python文件讀寫的內(nèi)容,這部分內(nèi)容特別常用,掌握后對工作和實戰(zhàn)都大有益處,學(xué)習(xí)是循序漸進的過程,欲速則不達
    2020-01-01
  • python可視化之顏色映射詳解

    python可視化之顏色映射詳解

    Python的可視化有很多種,這篇文章主要介紹了Python可視化的顏色映射,非常不錯,具有一定的參考借鑒價值,需要的朋友可以參考下
    2021-09-09
  • Pytorch之contiguous的用法

    Pytorch之contiguous的用法

    今天小編就為大家分享一篇Pytorch之contiguous的用法,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧
    2019-12-12
  • 下載python中Crypto庫報錯:ModuleNotFoundError: No module named ‘Crypto’的解決

    下載python中Crypto庫報錯:ModuleNotFoundError: No module named ‘Cry

    Crypto不是自帶的模塊,需要下載。下面這篇文章主要給大家介紹了關(guān)于下載python中Crypto庫報錯:ModuleNotFoundError: No module named 'Crypto'的解決方法,文中通過圖文介紹的非常詳細,需要的朋友可以參考下。
    2018-04-04
  • 詳解Python各大聊天系統(tǒng)的屏蔽臟話功能原理

    詳解Python各大聊天系統(tǒng)的屏蔽臟話功能原理

    這篇文章主要介紹了詳解Python各大聊天系統(tǒng)的屏蔽臟話功能原理,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。
    2016-12-12
  • Python?pandas中read_csv參數(shù)示例詳解

    Python?pandas中read_csv參數(shù)示例詳解

    使用pandas做數(shù)據(jù)處理的第一步就是讀取數(shù)據(jù),數(shù)據(jù)源可以來自于各種地方,csv文件便是其中之一,下面這篇文章主要給大家介紹了關(guān)于Python?pandas中read_csv參數(shù)詳解的相關(guān)資料,需要的朋友可以參考下
    2023-01-01
  • Python利用arcpy模塊實現(xiàn)柵格的創(chuàng)建與拼接

    Python利用arcpy模塊實現(xiàn)柵格的創(chuàng)建與拼接

    這篇文章主要為大家詳細介紹了如何基于Python語言arcpy模塊,實現(xiàn)柵格影像圖層建立與多幅遙感影像數(shù)據(jù)批量拼接(Mosaic)的操作,感興趣的可以了解一下
    2023-02-02
  • python類名和類方法cls修改類變量的值

    python類名和類方法cls修改類變量的值

    這篇文章主要介紹了python類名和類方法cls修改類變量的值,通過類對象是無法修改類變量的值的,本質(zhì)其實是給類對象新添加?name?和?age?變量,下文更多的相關(guān)介紹需要的小伙伴可任意參考一下
    2022-04-04
  • pandas 透視表中文字段排序方法

    pandas 透視表中文字段排序方法

    今天小編就為大家分享一篇pandas 透視表中文字段排序方法,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧
    2018-11-11

最新評論

无为县| 明光市| 盈江县| 彭州市| 温州市| 江安县| 咸阳市| 武胜县| 哈尔滨市| 蒙城县| 九江市| 汉川市| 九龙城区| 金昌市| 元阳县| 甘肃省| 潮州市| 广丰县| 巫山县| 大宁县| 公主岭市| 南阳市| 安顺市| 崇义县| 临清市| 晋中市| 富蕴县| 东阿县| 若尔盖县| 汤原县| 昭通市| 兴安盟| 天等县| 全椒县| 西林县| 顺昌县| 博罗县| 陆良县| 江达县| 中卫市| 乐东|