django에서 유저의 IP주소를 찾고자 합니다

조회수 5465회

발생하는 문제 및 실행환경

django에서 유저의 IP주소를 찾아내야 합니다

제 코드는 실행하면 에러가 뜨는데 어디서 문제가 있는지 모르겠습니다.

소스코드

# Create your views
from django.contrib.gis.utils import GeoIP
from django.template import  RequestContext
from django.shortcuts import render_to_response


def home(request):
  g = GeoIP()
  client_ip = request.META['REMOTE_ADDR']
  lat,long = g.lat_lon(client_ip)
  return render_to_response('home_page_tmp.html',locals())

에러내용

KeyError at /mypage/
    'REMOTE_ADDR'
    Request Method: GET
    Request URL:    http://mywebsite.com/mypage/
    Django Version: 1.2.4
    Exception Type: KeyError
    Exception Value:    
    'REMOTE_ADDR'
    Exception Location: /mysite/homepage/views.py in home, line 9
    Python Executable:  /usr/bin/python
    Python Version: 2.6.6
    Python Path:    ['/mysite', '/usr/local/lib/python2.6/dist-packages/flup-1.0.2-py2.6.egg', '/usr/lib/python2.6', '/usr/lib/python2.6/plat-linux2', '/usr/lib/python2.6/lib-tk', '/usr/lib/python2.6/lib-old', '/usr/lib/python2.6/lib-dynload', '/usr/local/lib/python2.6/dist-packages', '/usr/lib/python2.6/dist-packages', '/usr/lib/pymodules/python2.6']
    Server time:    Sun, 2 Jan 2011 20:42:50 -0600

1 답변

  • 좋아요

    0

    싫어요
    채택 취소하기

    django-ipware를 사용

    IPv4와 IPv6 모두 지원하고, python 2/3에서도 쓸 수 있는 걸로 압니다.

    설치는 pip install django-ipware로 해 주시고, 코드는

    from ipware.ip import get_ip
    ip = get_ip(request)
    if ip is not None:
        print "찾았다"
    else:
        print "못찾았다"
    

    로 살짝만 수정해주시면 됩니다.

    이게 안된다면 다음 방법을 쓰세요. 위의 코드보다는 보기 힘들겁니다..

    def get_client_ip(request):
        x_forwarded_for = request.META.get('HTTP_X_FORWARDED_FOR')
        if x_forwarded_for:
            ip = x_forwarded_for.split(',')[0]
        else:
            ip = request.META.get('REMOTE_ADDR')
        return ip
    

답변을 하려면 로그인이 필요합니다.

프로그래머스 커뮤니티는 개발자들을 위한 Q&A 서비스입니다. 로그인해야 답변을 작성하실 수 있습니다.

(ಠ_ಠ)
(ಠ‿ಠ)