Friday, August 7, 2009

Postgres from python

This snippet contains no validation whatsoever.

import psycopg2

connection = psycopg2.connect('dbname=product user=postgres host=127.0.0.1')
mark = connection.cursor()
query = """INSERT INTO PRODUCT(product_id, product, attribute) VALUES(%d, '%s', '%s')"""
statement = query % (1, "name", "attribute")
mark.execute(statement)
connection.commit()

Thursday, August 6, 2009

GeoIP with Maxmind's Geolite

I was searching for a python tool to determine approximate location from IP address.


You need to download 3 tars:

a. Geolite C library- Python module internally uses this C library
http://geolite.maxmind.com/download/geoip/api/c/GeoIP.tar.gz

tar -xvzf GeoIP.tar.gz
cd GeoIP-1.4.6
./configure --libdir=/usr/lib/python2.5/site-packages/
make
make install

b. Python api:
http://geolite.maxmind.com/download/geoip/api/python/GeoIP-Python-1.2.4.tar.gz

tar -xvzf GeoIP-Python-1.2.4.tar.gz
cd GeoIP-Python-1.2.4

# Edit setup.py to adjust the library_dirs and include_dirs
library_dirs = ['/usr/lib/python2.5/site-packages/'],

python setup.py build
sudo python setup.py install

c. Download Data file (This you probably need to update periodically)
http://geolite.maxmind.com/download/geoip/database/GeoLiteCity.dat.gz

Test your setup
--------------------------
(From: http://stackoverflow.com/questions/1163136/how-to-detect-the-country-and-city-of-a-user-accessing-your-site)

I do not completely understand how variables in library are accessed from python.. So I export this variable
export LD_LIBRARY_PATH=/usr/lib/python2.5/site-packages/

import GeoIP
gi = GeoIP.open("GeoLiteCity.dat", GeoIP.GEOIP_INDEX_CACHE | GeoIP.GEOIP_CHECK_CACHE)
print gi.record_by_name("74.125.67.100") # a www.google.com IP

{'city': 'Mountain View', 'region_name': 'California', 'region': 'CA', 'area_code': 650, 'time_zone': 'America/Los_Angeles', 'longitude': -122.05740356445312, 'country_code3': 'USA', 'latitude': 37.419200897216797, 'postal_code': '94043', 'dma_code': 807, 'country_code': 'US', 'country_name': 'United States'}