[PYTHON] How to use Django's GeoIp2

How to use GeoIp2 settings in Django

Introduction

  1. Django 1.9 and above

  2. You need to get the GeoIp2-database download from the MAXMIND official website. You can download free files by registering as a user.

MAXMIND Official Website

Setting

Install django-geoip2-extras

# cmd
pip install django-geoip2-extras

Edit setting.py

Add GeoIP2 Middleware

# setting.py

MIDDLEWARE = [
    ~
    'django.contrib.sessions.middleware.SessionMiddleware',

    #Add GeoIP2 Middleware after Session Middleware
    'geoip2_extras.middleware.GeoIP2Middleware',
    ~
]

Set GEOIP_PATH

# setting.py

GEOIP_PATH = os.path.join('The path where mmdb is located')

How to use


#Import geoip2
from django.contrib.gis import geoip2

#Instantiation
geo_ip2 = geoip2.GeoIP2()

#Set the domain name or IP address in the argument
geo_ip2.city(query)
geo_ip2.country(query)
geo_ip2.country_code(query)
geo_ip2.country_name(query)

Reference site

django-geoip2-extras 1.2(PyPI) GeoIP2 (Django official documentation)

Recommended Posts

How to use Django's GeoIp2
How to use xml.etree.ElementTree
How to use Python-shell
How to use tf.data
How to use virtualenv
How to use Seaboan
How to use image-match
How to use shogun
How to use Virtualenv
How to use numpy.vectorize
How to use pytest_report_header
How to use ManyToManyField with Django's Admin
How to use partial
How to use Bio.Phylo
How to use SymPy
How to use x-means
How to use WikiExtractor.py
How to use virtualenv
How to use Matplotlib
How to use iptables
How to use numpy
How to use TokyoTechFes2015
How to use venv
How to use Pyenv
How to use list []
How to use python-kabusapi
How to use OptParse
How to use return
How to use dotenv
How to use pyenv-virtualenv
How to use Go.mod
How to use imutils
How to use import
How to use Qt Designer
How to use search sorted
python3: How to use bottle (2)
Understand how to use django-filter
How to use the generator
How to use FastAPI ③ OpenAPI
How to use Python argparse
How to use IPython Notebook
How to use Pandas Rolling
[Note] How to use virtualenv
How to use redis-py Dictionaries
[Python] How to use checkio
[Go] How to use "... (3 periods)"
[Python] How to use input ()
How to use the decorator
[Introduction] How to use open3d
How to use Python lambda
How to use Jupyter Notebook
[Python] How to use virtualenv
python3: How to use bottle (3)
python3: How to use bottle
How to use Google Colaboratory
How to use Python bytes
How to use the exists clause in Django's queryset
How to use the zip function
How to use the optparse module
How to use SWIG from waf
Summary of how to use pandas.DataFrame.loc