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.
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'}