Django记录网站访问量
日期: 2024-01-11 | 作者: admin | 浏览: 251

想着在站点里统计下不同IP的访问总数,查了下相关资料,Django的可以这么操作,同时发现有个Ip2region 很给力,可以转换IP到相应区域,访客信息一目了然。

1. 新增访客模型
# 访客信息
class Visitor(models.Model):
    access_time = models.DateTimeField('访问时间', default=timezone.now)
    ip = models.GenericIPAddressField('访客IP', max_length=50)
    area = models.CharField('访客区域', max_length=50)
    browser = models.CharField('浏览器', max_length=500)

    class Meta:    
        ordering = ('-access_time',)

    def __str__(self):
        return self.ip
2. 调用IP2region相关功能实现IP到地区的转换
# 根据IP获取地址
def get_area_info(ip):
    db_path = Path(__file__).resolve().parent.parent / "ip2region.xdb"
    searcher = XdbSearcher(dbfile=db_path)
    # 2. 执行查询
    try:
        region_str = searcher.searchByIPStr(ip)
    except OSError:
        region_str = 'Unknown IPAddress'
    # 3. 关闭searcher
    searcher.close()
    return region_str
3.  记录访客IP
# 记录访问IP
def visitor_info(request):
    ipinfo = request.META.get('HTTP_X_FORWARDED_FOR')
    browser = request.META.get('HTTP_USER_AGENT', 'Unknown Browser')

    if ipinfo:
        ip = ipinfo.split(',')[0]
    else:
        ip = request.META.get('REMOTE_ADDR')
    area = get_area_info(ip)

    # 12小时内重复IP不统计
    time_interval = timezone.now() - timedelta(hours=12)
    have = Visitor.objects.filter(ip=ip).filter(access_time__gte=time_interval)
    if have:
        pass
    else:
        Visitor.objects.create(access_time=timezone.now(), ip=ip, area=area, browser=browser)
4. 调用及显示
# 站点首页
def index(request):
    # 调用访问IP记录
    visitor_info(request)
    # 总访问数
    count= Visitor.objects.count()
    return render(request, 'index.html', {'title': '首页', 'count': count})