Skip to content

Instantly share code, notes, and snippets.

@hbasria
Created July 18, 2019 14:46
Show Gist options
  • Select an option

  • Save hbasria/14185a05abe2429a94c2b760e0899086 to your computer and use it in GitHub Desktop.

Select an option

Save hbasria/14185a05abe2429a94c2b760e0899086 to your computer and use it in GitHub Desktop.
python SQLite custom function
import sqlite3
from netaddr import IPNetwork
def is_private_ip(value):
return IPNetwork(value).is_private()
connection = sqlite3.connect(':memory:')
cur = connection.cursor()
cur.execute("""
CREATE TABLE ip_prefix
( id INTEGER PRIMARY KEY AUTOINCREMENT,
prefix VARCHAR NOT NULL,
description VARCHAR
);
""")
cur.execute('INSERT INTO ip_prefix VALUES(1,"8.8.8.8/24", "ip1")')
cur.execute('INSERT INTO ip_prefix VALUES(2,"192.168.1.1/24", "ip2")')
connection.create_function("is_private_ip", 1, is_private_ip)
if __name__ == '__main__':
print(cur.execute('SELECT * FROM ip_prefix').fetchall())
print(cur.execute('SELECT *, is_private_ip(prefix) FROM ip_prefix').fetchall())
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment