Login

WorldIP - access to IP database over API

Author:
Alrond
Posted:
September 11, 2008
Language:
Python
Version:
1.0
Score:
0 (after 0 ratings)

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: WIPmania.com

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
#!/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"

More like this

  1. Template tag - list punctuation for a list of items by shapiromatron 11 months ago
  2. JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 11 months, 1 week ago
  3. Serializer factory with Django Rest Framework by julio 1 year, 6 months ago
  4. Image compression before saving the new model / work with JPG, PNG by Schleidens 1 year, 6 months ago
  5. Help text hyperlinks by sa2812 1 year, 7 months ago

Comments

Please login first before commenting.