用户IP访问次数统计

技术源于生活,服务生活

线上地址:https://api.imibi.cn

Redis存储

1.使用Redis的0号数据库,数据格式是hash.

import redis
con = redis.Redis(host='localhost', port=6379, decode_responses=True, db=0)

2.hash的键值对分别是key=ip,value=访问次数

数据统计

数据统计函数


def set_len_data(ip):
    """访问次数统计"""
    ip_lens = con.hmget('ip', ip)[0]
    if ip_lens == None:
        '未记录IP'
        ip_dict = {ip: 1, 'is_active':0}
        lens_lens = 1
    else:
        ip_lens= int(ip_lens)+1
        ip_dict = {ip: ip_lens}
    con.hmset('ip', ip_dict)
    return ip_lens

通过resquest对象获取访问IP

ip = request.remote_addr  # 获取IP
ip_lens = set_len_data(ip)  # 存储到redis中

给URL路由添加访问次数统计方法

nginx

如果使用nginx反向代理,会导致用户访问的IP全部为127.0.0.1。

可以从$ proxy_add_x_forwarded_for中获取到用户的真实IP,这里需要修改nginx的 x_forwarded_for 

nginx配置

location / {
    proxy_set_header            Host $host;
    proxy_set_header            X-real-ip $remote_addr;
    proxy_set_header            X-Forwarded-For $proxy_add_x_forwarded_for;
}

名词解释:

$remote_addr 获取到上一级代理的IP
$proxy_add_x_forwarded_for
获取到结果例如:(61.151.178.76, 10.10.10.89),第一个是用户的真实IP,第二个是一级代理的IP,依此类推。
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值