Django,捕获客户端IP获取

时间:2017-08-20 11:16:09

标签: python django django-rest-framework

我正在尝试捕获客户端IP并将其存储到我的数据库中的日志中,我尝试使用像ipware这样的软件包但我在运行应用程序时仍然遇到同样的错误

  File "/Users/abdul/Documents/tutorial/drftutorial/urls.py", line 2, in <module>
from . import views
File "/Users/abdul/Documents/tutorial/drftutorial/views.py", line 24, in <module>
class UserCreateView(generics.CreateAPIView):
File "/Users/abdul/Documents/tutorial/drftutorial/views.py", line 27, in UserCreateView
ip=get_client_ip(request)
File "/Users/abdul/Documents/tutorial/drftutorial/views.py", line 17, in get_client_ip
x_forwarded_for = request.META.get('HTTP_X_FORWARDED_FOR')
AttributeError: 'module' object has no attribute 'META'

我相信错误正在发生,因为我没有正确访问请求方法,我正在使用Django-restframework,我所遵循的教程在调用视图时没有传递请求对象。

这是我的代码:

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

class UserCreateView(generics.CreateAPIView):
    action = 'User registered'
    response1 = 'Success'
    ip=get_client_ip(request)
    print ip
    if ip is not None:
        ip="could not get IP"
    else:
        print(" got the IP!")
    print (" I am here!")
    Logadd(action,response1,ip)
    serializer_class = UserSerializer

1 个答案:

答案 0 :(得分:-1)

请试试这个:

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