Django 라이브러리 소개 - IP로 위치 나라 도시 정보 가져오기

유용한 장고 라이브러리 소개글, 일단 IP를 이용한 위치정보, 접속 브라우저 정보를 가져오는 라이브러리, 그리고 어뷰징등의 잘못된 접근을 간단하게 막아주는 ratelimit 기능을 소개해 보자. 

 

현재 듣고 있는 장고 강의에 소스에 포함된 내용을 공부할 겸 추려본다 - Django 실전 프로젝트 1 - URL Shortener 서비스 ( 패스트캠퍼스 )

 

Django 위치정보

IP나 도메인 주소 정보로 서비스되고 있는 위치 정보를 가져오는 라이브러리, 나라와 도시에 대한 정보를 별도 데이터베이스로 저장해서 관리해주고 있다. 주기적으로 이 DB를 가져와서 업데이트 하면 꽤 괜찮은 정확한 정보를 사용자들에게 보여 줄 수 있다. 위도 경도 정보도 가져올 수 있다.

 

Django settings.py 에 GEOIP_PATH 를 세팅해 둬야한다.

Grab the GeoLite2-Country.mmdb.gz and GeoLite2-City.mmdb.gz files and unzip them in a directory corresponding to the GEOIP_PATH setting.

 

당연히 라이브러리는 설치 해야 한다.

$ pip install geoip2

 

공식 문서에 있는 간단한 사용법은 여기에 옮겨둔다.

>>> from django.contrib.gis.geoip2 import GeoIP2
>>> g = GeoIP2()

## 간단하게 나라 이름, 코드 가져오기

>>> g.country('google.com')
{'country_code': 'US', 'country_name': 'United States'}

## 간단하게 도시 정보 가져오기

>>> g.city('72.14.207.99')
{'city': 'Mountain View',
'continent_code': 'NA',
'continent_name': 'North America',
'country_code': 'US',
'country_name': 'United States',
'dma_code': 807,
'is_in_european_union': False,
'latitude': 37.419200897216797,
'longitude': -122.05740356445312,
'postal_code': '94043',
'region': 'CA',
'time_zone': 'America/Los_Angeles'}

## 간단하게 위도 경도 정보 가져오기

>>> g.lat_lon('salon.com')
(39.0437, -77.4875)
>>> g.lon_lat('uh.edu')
(-95.4342, 29.834)
>>> g.geos('24.124.1.80').wkt
'POINT (-97 38)'

 

라이브러리 문서 페이지는 여기.

https://docs.djangoproject.com/en/3.2/ref/contrib/gis/geoip2/

 

Geolocation with GeoIP2 | Django documentation | Django

Django The web framework for perfectionists with deadlines. Overview Download Documentation News Community Code Issues About ♥ Donate

docs.djangoproject.com

MaxMind 사에서 제공되고 있는 라이브러리를 한번 더 wrapping 한 라이브러리, 원본 라이브러리 위치는 여기

https://geoip2.readthedocs.io/en/latest/

 

MaxMind GeoIP2 Python API — geoip2 4.4.0 documentation

Apache License, Version 2.0

geoip2.readthedocs.io

 

가고싶은 도시 런던

Chait Goli 님의 사진, 출처: Pexels