python3 通过ip查找所属城市 redis4.0.10

#coding=utf-8
###5.3 查找ip所属的城市以及国家###
import csv
import redis
import json
import time
conn = redis.Redis(host='10.40.143.201', port=6380, password='aAc22+4LLzYa8s/oWZlMvQ==')

# ip地址每8个二进制位被看作是无符号整数中的一个字节 其中IP地址最开头的8个二进制位为最高为
def ip_to_score(ip_address):
    score = 0
    for v in ip_address.split('.'):
        score = score * 256 + int(v, 10)
    return score


# 将ip地址转化为分值 因多个ip地址范围可能会被映射至同一个城市ID 所以程序在普通城市ID后面加上'_'字符以及有序集合目前已有城市ID数量
# 导入15分钟
def import_ips_into_redis(conn, filename):
    csv_file = csv.reader(open(filename, 'r'))
    for count, row in enumerate(csv_file):
        print(count, '---', row)
        start_ip = row[0] if row else ''
        if 'i' in start_ip.lower():
            continue
        if '.' in start_ip:
            start_ip = ip_to_score(start_ip)
        elif start_ip.isdigit():
            start_ip = int(start_ip, 10)
        else:
            continue
        city_id = row[2] + '_' + str(count)
        conn.zadd('ip2cityid:', city_id, start_ip)


# 在调用import_ips_into_redis()函数并将所有ip地址载入redis之后 我们将创建城市ID映射城市信息至散列
# 因为所有城市的信息格式都是固定的 并且不会随着时间变化而变化 所以我们将这些信息编码为JSON列表然后再进行存储
# 导入7分钟
def import_cities_to_redis(conn, filename):
    for row in csv.reader(open(filename, 'r', encoding='utf-8', errors='ignore')):
        print(row)
        if len(row) < 4 or not row[0].isdigit():
            continue
        row = [i for i in row]
        city_id = row[0]
        country = row[1]
        region = row[2]
        city = row[3]
        conn.hset('cityid2city:', city_id, json.dumps([city, region, country]))


# 将所需信息全部存储到redis中之后 接下来考虑的就是如何实现IP地址的查找功能
def find_city_by_ip(conn, ip_address):
    if isinstance(ip_address, str):
        ip_address = ip_to_score(ip_address)
    city_id = conn.zrevrangebyscore('ip2cityid:', ip_address, 0, start=0, num=1)
    if not city_id:
        return None
    # city_id = city_id[0].partition('_')[0]
    city_id = city_id[0].partition(b'_')[0]
    return json.loads(conn.hget('cityid2city:',city_id))
    # return city_id, type(city_id)

# print(conn.ping())
start = time.time()
print(find_city_by_ip(conn, '172.217.24.14'))
# time.sleep(1)
end = time.time()
print(end-start)
    原文作者:Smith_My_
    原文地址: https://blog.csdn.net/Smith_My_/article/details/81362086
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞