如何在数据库和django admin中存储IP地址

问题描述 投票:18回答:4

想存储每个来到网站的人的IP地址。这样做的最佳方法是什么?让我们说有模特

class ip(models.Model):
    pub_date = models.DateTimeField('date published')
    ip_address = models.GenericIPAddressField()

什么是模型或视图中的代码或我将其保存在数据库中的某个地方也希望使用类似于此的用户代理信息保存它。

django django-models django-admin ip-address user-agent
4个回答
17
投票

在views.py中:

views.朋友:

    ....

    x_forwarded_for = request.META.get('HTTP_X_FORWARDED_FOR')

    if x_forwarded_for:
        ipaddress = x_forwarded_for.split(',')[-1].strip()
    else:
        ipaddress = request.META.get('REMOTE_ADDR')
    get_ip= ip() #imported class from model
    get_ip.ip_address= ipaddress
    get_ip.pub_date = datetime.date.today() #import datetime
    get_ip.save()

8
投票

我使用中间件给了@Sahil Kalra的例子,

模型:

class IpAddress(models.Model):
    pub_date = models.DateTimeField('date published')
    ip_address = models. GenericIPAddressField()

中间件:

import datetime

class SaveIpAddressMiddleware(object):
    """
        Save the Ip address if does not exist
    """
    def process_request(self, 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')
        try:
            IpAddress.objects.get(ip_address=ip)
        except IpAddress.DoesNotExist:             #-----Here My Edit
              ip_address = IpAddress(ip_address=ip, pub_date=datetime.datetime.now())
              ip_address.save()
            return None

将中间件保存在项目文件夹中的某个位置,并在设置文件中添加此中间件。这是参考How to set django middleware in settings file


5
投票

您可以非常轻松地将IP地址提取到views.py中。

def get_ip_address(request):
    """ use requestobject to fetch client machine's IP Address """
    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')    ### Real IP address of client Machine
    return ip   


def home(request):
    """ your vies to handle http request """
    ip_address = get_ip_address(request)

3
投票

由于您要保存用户代理而不管正在调用的URL或视图,因此在视图或模型中编写此代码没有任何意义。

您应该编写一个可以为您完成工作的中间件。查看有关Django中间件的更多信息:https://docs.djangoproject.com/en/1.6/topics/http/middleware/

您想要覆盖自定义中间件的process_request()方法,以从请求对象获取IPaddress和useragent并将其存储在IP模型中

以上链接将为您提供绝对清晰的信息。

© www.soinside.com 2019 - 2024. All rights reserved.