欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

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)文章

  • Pytorch中如何調(diào)用forward()函數(shù)

    Pytorch中如何調(diào)用forward()函數(shù)

    這篇文章主要介紹了Pytorch中如何調(diào)用forward()函數(shù)問題,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教
    2023-02-02
  • Linux 下 Python 實現(xiàn)按任意鍵退出的實現(xiàn)方法

    Linux 下 Python 實現(xiàn)按任意鍵退出的實現(xiàn)方法

    這篇文章主要介紹了Linux 下 Python 實現(xiàn)按任意鍵退出的實現(xiàn)方法的相關(guān)資料,本文介紹的非常詳細,具有參考借鑒價值,需要的朋友可以參考下
    2016-09-09
  • Python 實現(xiàn)給圖片加文字或logo水印

    Python 實現(xiàn)給圖片加文字或logo水印

    本文主要為大家介紹了給圖片添加文字或者logo圖片水印的python工具,從而打造你的專屬圖片。代碼簡潔易懂,感興趣的小伙伴可以了解一下
    2021-11-11
  • PyTorch CNN實戰(zhàn)之MNIST手寫數(shù)字識別示例

    PyTorch CNN實戰(zhàn)之MNIST手寫數(shù)字識別示例

    本篇文章主要介紹了PyTorch CNN實戰(zhàn)之MNIST手寫數(shù)字識別示例,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧
    2018-05-05
  • python關(guān)閉windows進程的方法

    python關(guān)閉windows進程的方法

    這篇文章主要介紹了python關(guān)閉windows進程的方法,涉及Python調(diào)用系統(tǒng)命令操作windows進程的技巧,需要的朋友可以參考下
    2015-04-04
  • 用Python實現(xiàn)寫倒序輸出(任意位數(shù))

    用Python實現(xiàn)寫倒序輸出(任意位數(shù))

    這篇文章主要介紹了用Python實現(xiàn)寫倒序輸出(任意位數(shù)),具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教
    2022-05-05
  • Python如何實現(xiàn)機器人聊天

    Python如何實現(xiàn)機器人聊天

    這篇文章主要介紹了Python如何實現(xiàn)機器人聊天,幫助大家更好的理解和學(xué)習(xí)python,感興趣的朋友可以了解下
    2020-09-09
  • 如何用Python從桌面讀取二維碼信息詳解

    如何用Python從桌面讀取二維碼信息詳解

    二維碼作為一種信息傳遞的工具,在當(dāng)今社會發(fā)揮了重要作用,下面這篇文章主要給大家介紹了關(guān)于如何用Python從桌面讀取二維碼信息的相關(guān)資料,文中通過示例代碼介紹的非常詳細,需要的朋友可以參考下
    2021-10-10
  • 基于PyQt5制作數(shù)據(jù)處理小工具

    基于PyQt5制作數(shù)據(jù)處理小工具

    這篇文章主要和大家介紹了如何利用Python中的PyQt5模塊制作一個數(shù)據(jù)處理小工具,可以實現(xiàn)根據(jù)每個Excel數(shù)據(jù)文件里面的Sheet批量將數(shù)據(jù)文件合并成為一個匯總后的Excel數(shù)據(jù)文件,需要的可以參考一下
    2022-03-03
  • keras用auc做metrics以及早停實例

    keras用auc做metrics以及早停實例

    這篇文章主要介紹了keras用auc做metrics以及早停實例,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧
    2020-07-07

最新評論