#!/usr/bin/env python # Licensed under GPL 2.0 # worldip.py - access to WorldIP database over online-API """ This code shows how to get the country of users. It uses online API of WIPmania project. The WorldIP database provides real-world geographical location. Database is more correct than Whois records and Whois-based databases, that show geographic locations of network owners, and not the geographic location of Internet-connected PC or appliance itself. See more: http://www.wipmania.com API-format is very simple: http://api.wipmania.com/[IPADDR]?[URL] IPADDR - queried IP address. For example, your visitor's address. URL - your domain name. It will be used to control your daily limits. For example: Google.com is enquiring about the IP address 123.45.67.89 The query will look as follows: http://api.wipmania.com/123.45.67.89?google.com As a result: a double-character country code, “KR” for South Korea. In views add: from worldip import getUserCountry remote_addr = request.META.get('REMOTE_ADDR',"127.0.0.1") country = getUserCountry(remote_addr) Add in settings.py your URL as SITE_URL, like SITE_URL = "http://www.google.com" """ from urllib2 import urlopen, Request import re, socket from django.conf import settings domain_re = re.compile('^(http|https):\/\/?([^\/]+)') domain = domain_re.match(settings.SITE_URL).group(2) def getUserCountry(ip): url = "http://api.wipmania.com/" + ip + "?" + domain socket.setdefaulttimeout(5) headers = {'Typ':'django','Ver':'1.0','Connection':'Close'} try: req = Request(url, None, headers) urlfile = urlopen(req) land = urlfile.read() urlfile.close() return land[:2] except Exception: return "XX"