ip_search.py 887 B

1234567891011121314151617181920212223242526272829
  1. from ip2Region import Ip2Region
  2. def ip_search(ip, region_type, algorithm='btree'):
  3. db_file = './ip2region.db'
  4. searcher = Ip2Region(dbfile=db_file)
  5. try:
  6. if algorithm == "binary":
  7. data = searcher.binarySearch(ip.strip())
  8. elif algorithm == "memory":
  9. data = searcher.memorySearch(ip.strip())
  10. else:
  11. data = searcher.btreeSearch(ip.strip())
  12. region = data['region'].decode('utf-8').split('|')
  13. if region_type == 'country':
  14. return region[0].strip()
  15. if region_type == 'province':
  16. return region[2].strip()
  17. if region_type == 'city':
  18. return region[3].strip()
  19. except Exception as e:
  20. print(e)
  21. return None
  22. if __name__ == '__main__':
  23. ip = '101.105.35.57'
  24. res = ip_search(ip=ip, region_type='city', algorithm='binary')
  25. print(res)