appliedsec / pygeoip

DEPRECATED: Pure Python API for Maxmind's binary GeoIP databases
https://github.com/appliedsec/pygeoip
GNU Lesser General Public License v3.0
481 stars 111 forks source link

Correctly using pygeoip inside a Django app #67

Closed aaaagrawal closed 10 years ago

aaaagrawal commented 10 years ago

Hi, I want to use pygeoip library in one of my Django projects so as to know visitor's city and then offering him dynamic webpage based on the city. So these are my queries -

  1. What should be the database format - binary or csv? - http://dev.maxmind.com/geoip/legacy/geolite/
  2. I am using pygeoip in one of the views inside a Django app. What's the best place to keep the database inside the Django project? Thanks.
tiwilliam commented 10 years ago
  1. pygeoip is using the binary database
  2. Either you check in the database into your repository, it's about 700K in size. If repository size is a concern you can always create a separate shallow repository or use the OS provided version if any.
aaaagrawal commented 10 years ago

@tiwilliam : This is what I have in my views.py -

import pygeoip

# Create your views here.
def get_client_ip(request):
    x_forwarded_for = request.META.get('HTTP_X_FORWARDED_FOR')
    if x_forwarded_for:
        ip = x_forwarded_for.split(',')[0]
    else:
        ip = request.META.get('REMOTE_ADDR')
    return ip

def get_city(request):
    ip = get_client_ip(request)
    gi = pygeoip.GeoIP('GeoLiteCity.dat')
    geo_info_dict = gi.record_by_addr(str(ip))
    return HttpResponse("Your IP address is " + str(ip) + "\n" + "Your city is " + geo_info_dict['city'])

And I have the binary version file GeoLiteCity.dat in the same application directory in which views.py resides. But I am getting this IOerror - [Errno 2] No such file or directory: 'GeoLiteCity.dat'. Any clue if I am doing something wrong?

tiwilliam commented 10 years ago

I would guess your current work directory isn't the same as application root. If you want to debug, use os.getcwd() to find out where you are or use a absolute path.

aaaagrawal commented 10 years ago

@tiwilliam : Thanks. Using absolute dynamic path worked. This issue can be closed then.