2
0

More than 3 years have passed since last update.

[Python]GeoLite2を用いたIPアドレス国判定方法 メモ

Posted at
  • IPアドレスから国判定を行う方法についてメモする。

事前準備

  • GeoLite2データベースのダウンロード

    • こちらでアカウントを作成し、「GeoLite2 City」データをダウンロードする。
    • データを解凍し、「GeoLite2-City.mmdb」を取得する。
  • GeoLiteAPIインストール

  pip install geoip2

コードmain.py

  • HTTP X-Forwarded-ForヘッダーにIPアドレスが付与されるケースを想定し、ヘッダーから取得した値から国コードを返却するAPIを作成する。

    • API構築用フレームワークとして、FastAPIを使用。
    • エラーハンドリング未実施。
    • 複数プロキシ経由時の対応は別途必要となる。
  import geoip2.database
  from fastapi import FastAPI, Request
  app = FastAPI()


  # API
  @app.get("/country_code")
  def search_shop(request: Request):
      ipaddress = request.headers['X-Forwarded-For']
      reader = geoip2.database.Reader('GeoLite2-City.mmdb')
      country_code = reader.city(ipaddress).country.iso_code
      response = {"country": country_code}
      return response

動作確認

  • API起動
  uvicorn main:app --reload
  INFO:     Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit)
  INFO:     Started reloader process [18624] using statreload
  INFO:     Started server process [10596]
  INFO:     Waiting for application startup.
  INFO:     Application startup complete.
  • リクエスト
  GET /country_code HTTP/1.1
  Host: localhost:8000
  Content-Type: application/json
  X-Forwarded-For: xxx.xxx.xxx.xxx
  • レスポンス
  {
      "country": "JP"
  }

参考情報

2
0
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
2
0