SQLAlchemy Query to find IP from IP range in Bulk

The following code snippet shows how to make bulk query of IP from IP start and end range from a database table using SQLAlchemy in Python:

We assume that the IP start and end range are saved in the form of integers in the database.

from sqlalchemy import and_, or_

ip_addrs = [

filters = []
#ip addresses in integer format
ip_addrs_integer = []
query = session.query(IpTable)
for ip in ip_addrs:
    ip_integer = ip_to_integer(ip)
    filters.append(and_(IpTable.start_integer_ip <= ip_integer, IpTable.end_integer_ip >= ip_integer))
ip_results = query.filter(or_(*filters)).limit(50).all()
for ip_integer in ip_addrs_integer:
    for ip_res in ip_results:
        if ip_res.start <= ip_integer and ip_res.end >= ip_integer:
            ip_res.ip = integer_to_ip(ip_integer)
#print ip details obtain from database
for ip_detail in ip_results:
    print("ip =", ip_detail.ip) 
    print("isp =", ip_detail.isp) 
    print("country =", ip_detail.country)   

The above code requires conversion of IP to integer and integer to IP. Learn how to do it here.