Reputation: 390
I'm trying to play around with GeoIP2 for Django, which require you to set the path to your country and city datasets in a GEOIP_PATH
setting. My issue is that I don't know where I'm supposed to put this setting so that something like the Python shell can see it.
I assume it would go in settings.py
, but I'm unsure as to the syntax for this particular module, and the Django documentation is absolute rubbish regarding this.
Upvotes: 2
Views: 4425
Reputation: 477
Simple steps I found
tar -xzf zip_file_name.tar.gz
in your consoleviews.py
for whichever app you need it for, implement like below.
from django.contrib.gis.geoip2 import GeoIP2
def index(request):
g = GeoIP2('GeoLite2-Country_20223519') #Enter folder name
country_code = g.country_code('15.194.1.177') #Enter IP address
Upvotes: 1
Reputation: 4869
You're correct that it should be placed inside the settings.py
file in Django. You should be able to find this file somewhere in your Django project/app. You then place the following in that file:
GEOIP_PATH = '/path/to/your/geoip/datafiles'
GEOIP willl then be able to locate the files it requires for usage in the application.
Note: If you already have a Django project set up you can start at step 10.
Make sure you have Python installed (I'm using Python 3.5.1 for this answer), inlucding pip
.
Install virtualenvwrapper: pip install virtualenvwrapper-win
(or pip install virtualenvwrapper
for non-windows install)
Make a virtual environment for your project: mkvirtualenv GeoIP
Install Django for this project: pip install django
To check the installation succeeded execute django-admin --version
, this should show you the version of the Django installtion, which is 1.9.1
for me. If you do not see this, make sure your python installation is correct.
Create a directory where you want your projects to be saved. In my case I made a directory called Django: mkdir Django
Move to this directory: cd Django
Create a Django project: django-admin startproject geoip_test
Move to the new directory Django created for you: cd geoip_test
Install geoip2: pip install geoip2
Create a directory to store the required datasets. Please note that these have to be unzipped: mkdir geoip
. Place the files you downloaded and unzipped in this directory.
Start a Django Python shell: python manage.py shell
Import GeoIP2: >>> from django.contrib.gis.geoip2 import GeoIP2
Create a GeoIP2
object by instantiating a class with a path to the location of the files you downloaded: >>> g = GeoIP2('geoip')
Test that everything works: >>> g.country('google.com')
{'country_code': 'US', 'country_name': 'United States'}
Upvotes: 11