LoginSignup
0
1

More than 3 years have passed since last update.

DjangoのGeoIp2操作方法

Last updated at Posted at 2020-03-26

DjangoでのGeoIp2の設定から使い方

はじめに

  1. Django1.9以上

  2. GeoIp2-databaseのダウンロードをMAXMIND公式サイトから入手する必要がある。
    ユーザー登録を行うことで無償ファイルをダウンロードすることができる。

MAXMIND公式サイト

設定

django-geoip2-extrasのインストール

# cmd
pip install django-geoip2-extras

setting.pyを編集

GeoIP2Middlewareを追加する

# setting.py

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

    # SessionMiddlewareの後にGeoIP2Middlewareを追加する
    'geoip2_extras.middleware.GeoIP2Middleware',
    ~
]

GEOIP_PATHを設定する

# setting.py

GEOIP_PATH = os.path.join('mmdbを配置しているパス')

使い方


# geoip2をインポート
from django.contrib.gis import geoip2

# インスタンス化
geo_ip2 = geoip2.GeoIP2()

# 引数にはドメイン名またはipアドレスを設定する
geo_ip2.city(query)
geo_ip2.country(query)
geo_ip2.country_code(query)
geo_ip2.country_name(query)

参考サイト

django-geoip2-extras 1.2(PyPI)
GeoIP2(Django公式ドキュメント)

0
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
1