blockinator/sqlite.py

47 lines
1.5 KiB
Python
Raw Normal View History

2012-05-21 19:08:04 +01:00
#!/usr/bin/python
2013-07-13 08:44:35 +01:00
"""Script to create a SQLite DB from the blocklist data."""
2012-05-21 19:08:04 +01:00
import blocklist
import sys
import logging
2013-07-13 08:44:35 +01:00
if sys.version_info >= (2, 5):
2012-05-21 19:08:04 +01:00
import sqlite3
else:
from pysqlite2 import dbapi2 as sqlite3
class SQLiteBlockList(blocklist.BlockList):
"""New class to extend the main BlockList class for implementation with Varnish."""
def export(self):
2013-07-13 08:44:35 +01:00
"""Exports blocklist criteria to a SQLite file."""
2012-05-21 19:08:04 +01:00
2013-07-13 08:44:35 +01:00
try:
database = sqlite3.connect(self.config.get("sqlite", "database"))
cur = database.cursor()
2012-05-21 19:08:04 +01:00
2013-07-13 08:44:35 +01:00
cur.execute("CREATE TABLE IF NOT EXISTS blocklist(remote_ip VARCHAR(15), forwarded_ip VARCHAR(15), useragent VARCHAR(256), cookie VARCHAR(1024), PRIMARY KEY(remote_ip))")
2012-05-21 19:08:04 +01:00
2013-07-13 08:44:35 +01:00
cur.execute("DELETE FROM blocklist")
2012-05-21 19:08:04 +01:00
2013-07-13 08:44:35 +01:00
for item in self.data.values():
if item["useragent"] == 'NULL':
item["useragent"] = '(null)'
cur.execute("INSERT INTO blocklist VALUES ('%s', '%s', '%s', '%s')" % (item["remote_ip"], item["forwarded_ip"], item["useragent"], item["cookie"]))
database.commit()
cur.close()
except sqlite3.Error, error:
logging.error("There was a problem exporting the data to SQLite. %s", error)
2012-05-21 19:08:04 +01:00
2013-07-13 08:44:35 +01:00
def main():
"""Main program loop."""
block_list = SQLiteBlockList()
2012-05-21 19:08:04 +01:00
2013-07-13 08:44:35 +01:00
block_list.read("http://example.com/default/blocks.txt")
2012-05-21 19:08:04 +01:00
2013-07-13 08:44:35 +01:00
block_list.export()
2012-05-21 19:08:04 +01:00
sys.exit(0)
2013-07-13 08:44:35 +01:00
if __name__ == "__main__":
main()